2

I have some variables and constants in a config file that I want to use in a method of a class in another both config.php and myclass.phpare in the same folder.

config.php

<?php
$a=1; 

myclass.php

class MyClass
{
  protected function a () {
   include_once('config.php');
   echo $a; //$a is undefined here 
  }
}

Is there a better approach for this?

1
  • you can also return a variable (an array maybe?) from an included file. See example #5 in manual about include Commented Aug 20, 2016 at 13:52

1 Answer 1

1

You can create another class in your config file and it will serve as a wrapper for all your config values and operations. This is the best approach also if you are giving value to OOP in your project development.

config.php

<?php
/**
 * PhpDoc...
 */
class YourConfig
{
  /**
   * Your constant value
   */
  const DB_HOST = 'localhost';

  /**
   * @var string Some description
   */
  private $layout = 'fluid';

  /**
   * Your method description
   * @return string layout property value
   */
  public function getLayout()
  {
    return $this->layout;
  }
}

myclass.php

<?php
/**
 * PhpDoc
 */
class MyClass
{
  private $config;

  public function __construct()
  {
    require_once( __DIR__ . '/config.php' );
    $this->config = new Config();
  }

  protected function a()
  {
    // get a config
    echo $this->config->getLayout();
  }
}

You can use and extend this approach for what/however you want.

Sign up to request clarification or add additional context in comments.

1 Comment

looks very clean .Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.