我知道以下内容可能会在其他地方引起问题,而且可能是不好的设计,但我仍然想知道为什么这样做失败了(为了自己的学习):
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();
错误是
在非对象上下文中使用$this
显然,$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();
__callStatic() 在静态上下文中调用不可访问方法时触发。
- 您的方法是公共的,将其更改为私有/受保护的,它将按您的期望工作 ;) 参考:https://www.php.net/manual/en/language.oop5.overloading.php#object.callstatic - jave.web