在以下类上调用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 dump在函数和错误中的输出。
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']
的属性,该属性不存在。将Config::get()
方法的最后一部分更改为:
foreach($parts as $part) {
$path .= '["'.$part.'"]';
}
return static::$$path;
:
$data = static::$config;
foreach ($parts as $part) {
$data = $data[$part];
}
return $data;
,它会像你想要的那样工作。虽然这不是一个很好的方法,但使用像Symfony的PropertyAccess组件这样的现有解决方案要好得多。