Adam Copley Adam Copley - 3 months ago 8
PHP Question

Access to undeclared static property: Config::$config["modules"] - even though it is defined and has an element named modules

How come I get the above error when calling

Config::get('modules');
on the following class?

The function works fine if I just return
static::$config
however when I try to return it's elements I get the error, even though it's definitely defined.

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;

}
}


output of var dumps in functions and error.

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

Answer

You can't access multidimensional array using variable variables' syntax. PHP is searching for property named $config['modules'] which does not exist. Change the last part of your Config::get() method from:

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

return static::$$path;

to:

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

return $data;

and it will work like you wanted. It's not a very good approach though, it's much better to use established solutions like Symfony's PropertyAccess component.

Comments