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 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决