Question

I am making a really silly error that I have no idea why.

I include a file right before a class declaration like this :

require_once('assets.php') //php_include_path is set to the correct folder and the file loads
class A{


function __construct(){
var_dump($assets); // dumps NULL
}
}

In assets.php, I have an array like this:

$assets['file'] = array('abc','qrd');

So why am I getting NULL here?

Was it helpful?

Solution

There are two methods I would choose for this, depending on on your situation, you can decide what works best.

Use assets as an argument to the class constructor. $assets will only be available in the constructor unless you use a class property like below.

require_once('assets.php');
class A{
  function __construct($assets){
    var_dump($assets);
  }
}
$a = new A($assets);

or

Put the require in the constructor. This example also features a class property so you can use $this->_assets in all of the class's methods.

class A{
  protected $_assets;
  function __construct(){
    require_once('assets.php');
    $this->_assets = $assets;
    var_dump($this->_assets);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top