我知道以下内容可能会在其他地方造成问题,并且可能是糟糕的设计,但我仍然想知道为什么会失败(为了我自己的启发):
class Test {
// singleton
private function __construct(){}
private static $i;
public static function instance(){
if(!self::$i){
self::$i = new Test();
}
return self::$i;
}
// pass static requests to the instance
public static function __callStatic($method, $parameters){
return call_user_func_array(array(self::instance(), $method), $parameters);
}
private $someVar = 1;
public function getSomeVar(){
return $this->someVar;
}
}
print Test::getSomeVar();
错误是Using $this when not in object context
显然 $this 在静态方法中是不可用的,但是静态方法通过 call_user_func_array 将它传递给实例方法调用,这应该使 $this 成为实例......
/编辑
我知道 $this 在静态上下文中不可用。但是,这有效:
print call_user_func_array(array(Test::instance(), 'getSomeVar'), array());
这正是 __callStatic 重载中发生的事情,所以有些不对劲......
/编辑 2
范围肯定会被奇怪地处理。如果您将单例实例拉到任何其他类,它会按预期工作:
class Test {
// singleton
private function __construct(){}
private static $i;
public static function instance(){
if(!self::$i){
self::$i = new Blah();
}
return self::$i;
}
// pass static requests to the instance
public static function __callStatic($method, $parameters){
return call_user_func_array(array(static::instance(), $method), $parameters);
}
}
class Blah {
private $someVar = 1;
public function getSomeVar(){
return $this->someVar;
}
}
print Test::getSomeVar();