-1

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?

Parijat Kalia
  • 4,929
  • 10
  • 50
  • 77
  • possible duplicate of [Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – deceze Apr 14 '14 at 18:24
  • thats because of scope and in addition u should get undefined variable $assets as notice if the error reporting is on for notice. – Abhik Chakraborty Apr 14 '14 at 18:24
  • Why not `return` the array to a variable in the local script and pass it into the constructor of the class `__construct($assets)`... – War10ck Apr 14 '14 at 18:33

1 Answers1

1

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);
  }
}
Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95
  • Thanks Devon. Both solutions seem good. Out of curiosity, I have multiple class files with a require_once statement. right before the Class is declared. These require_once files have Classes within them, so in the constructors of the including files class, I am able to create objects of the require_once file's class without having to do any of the aforementioned techniques. But somehow this does not work for arrays, how is that possible ? – Parijat Kalia Apr 14 '14 at 18:44
  • Can you update your original post with an example? It might be easier for me to wrap my head around what you're asking if I see it more visually. – Devon Bessemer Apr 14 '14 at 18:57