dozabg1616 2014-04-14 18:20
浏览 77
已采纳

尝试在PHP类构造函数中访问所需的文件数组

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?

  • 写回答

1条回答 默认 最新

  • dragonsun2005 2014-04-14 18:34
    关注

    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);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?