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

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳