【问题标题】:Access to undeclared static property: Config::$config["modules"] - even though it is defined and has an element named modules访问未声明的静态属性:Config::$config["modules"] - 即使它已定义并且有一个名为 modules 的元素
【发布时间】:2016-12-28 04:58:50
【问题描述】:

在下面的类上调用Config::get('modules');怎么会出现上述错误?

如果我只返回static::$config,该函数可以正常工作,但是当我尝试返回它的元素时,我得到了错误,即使它已经明确定义了。

class Config
{
    private static $config = NULL;
    private static $initialized = FALSE;

    public static function _init()
    {
        if(self::$initialized == TRUE)
        {
            return;
        }
        static::$config = $GLOBALS['config'];
        unset($GLOBALS['config']);

        var_dump(static::$config);
        static::$initialized = TRUE;
    }

    public static function get($property = '')
    {
        self::_init();
        var_dump(static::$config);

        $parts = explode('.', $property);

        $path = 'config';

        foreach($parts as $part)
        {
            $path .= '["'.$part.'"]';
        }

        return static::$$path;

    }
}

函数和错误中 var 转储的输出。

array(3) {
  ["APP_VERSION"]=>
  string(5) "0.0.1"
  ["database"]=>
  array(3) {
    ["dsn"]=>
    string(32) "mysql:host=localhost;dbname=test"
    ["user"]=>
    string(4) "root"
    ["pass"]=>
    string(0) ""
  }
  ["modules"]=>
  array(0) {
  }
}
array(3) {
  ["APP_VERSION"]=>
  string(5) "0.0.1"
  ["database"]=>
  array(3) {
    ["dsn"]=>
    string(32) "mysql:host=localhost;dbname=test"
    ["user"]=>
    string(4) "root"
    ["pass"]=>
    string(0) ""
  }
  ["modules"]=>
  array(0) {
  }
}

Fatal error: Access to undeclared static property: Config::$config["modules"] in C:\xampp\htdocs\project\system\classes\Config.php on line 37

【问题讨论】:

  • PHP 正在寻找一个名为 config["modules"] 的变量。它只是不能那样工作。

标签: php arrays class properties static


【解决方案1】:

您不能使用variable variables' 语法访问多维数组。 PHP 正在搜索不存在的名为 $config['modules'] 的属性。将 Config::get() 方法的最后一部分更改为:

foreach($parts as $part) {
    $path .= '["'.$part.'"]';
}

return static::$$path;

到:

$data = static::$config;
foreach ($parts as $part) {
    $data = $data[$part];
}

return $data;

它会像你想要的那样工作。虽然这不是一个很好的方法,但使用像Symfony's PropertyAccess 组件这样的既定解决方案要好得多。

【讨论】:

  • 感谢您的回答,我现在明白为什么它不适用于 VV 语法,以及使用循环访问 MD 数组的好方法!
  • 没问题,我用一个关于 Symfony PropertyAccess 组件的小评论更新了我的答案,我会推荐它而不是我在答案中写的代码。
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 2015-02-24
  • 2017-03-23
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多