0
我在寫一個最小的依賴注入類。然而,當我嘗試訪問一個靜態方法內的PHP給'未定義變量'通知的靜態屬性。該代碼是這樣的:訪問類內部的靜態屬性給出'未定義的變量'通知
class DI{
/**
* @var array $registry Class dependency resolving functions
*/
public static $registry = [];
/**
* @var array $instances Class instances for singleton classes
*/
public static $instances = [];
public static function register($className, $singleton, $resolve){
self::$registry[$className] = ['resolve' => $resolve, 'singleton' => $singleton];
}
public static function inject($className){
if(array_key_exists($className, self::$registry)){
if(array_key_exists($className, self::$instances)) {
return self::$instances[$className];
}
else{
// Problem occurs at that line:
$instance = self::$registry[$className]['resolve']();
if(self::$registry[$className]['singleton']){
self::$instances[$className] = $instance;
}
return $instance;
}
}
else{
return false;
}
}
}
但是如果我更改了該行這兩行問題就消失了:
$instance = self::$registry;
$instance = $instance[$className]['resolve']();
這是PHP的通知:
Notice: Undefined variable: registry in /var/www/lib/DI.class.php on line 32