【发布时间】:2012-11-07 00:02:31
【问题描述】:
我知道以下内容可能会在其他地方产生问题并且可能是糟糕的设计,但我仍然想知道为什么会失败(为了我自己的启发):
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
scope 肯定会被奇怪地处理。如果您将单例实例拉到任何其他类,它会按预期工作:
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();
【问题讨论】:
-
引用 PHP 手册:
__callStatic() is triggered when invoking inaccessible methods in a static context.- 您的方法是公开的,将其设为私有/受保护的,它将按您的预期工作;)参考:php.net/manual/en/… -
(当然,目标 static 方法也应该定义为 static )