I know the following could potentially create problems elsewhere and is probably bad design, but I still would like to know why this fails (for my own edification):
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();
The error is Using $this when not in object context
Obviously $this is unavailable from a static method, but the static method is handing it off to an instance method invokation via call_user_func_array, which should make $this the instance...
/EDIT
I'm aware that $this is not available in static context. However, this works:
print call_user_func_array(array(Test::instance(), 'getSomeVar'), array());
Which is exactly what's happening in the __callStatic overload, so something's amiss...
/EDIT 2
scope is definitely getting handled strangely. if you pull the singleton instance to any other class, it works as expected:
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();