$this not propagating in user_call_func_array() in PHP 5.3.4
I'm attempting to create an object which can be extended by additional classes after instantiation. I seem to have found a problem with user_call_func_array
(and this family of functions) not propagating the $this
variable properly.
Please consider the following:
// Base class
class baseClass {
public $some_value = 'foobar';
public function callManually() {
extensionClass::extendedMethod('hello')开发者_如何转开发;
}
public function callDynamically($class,$method) {
call_user_func_array("$class::$method",array('hello'));
}
}
// Extension class
class extensionClass {
public function extendedMethod($local_value) {
if(isset($this)) {
echo '$this is set. Local value = '.$local_value.'. Base value = '.$this->some_value."\n";
} else {
echo '$this is not set. Boo!'."\n";
}
}
}
// Create the base object and call extended method
$base_class = new baseClass;
$base_class->callManually();
$base_class->callDynamically('extensionClass','extendedMethod');
Both callManually()
and callDynamically()
invoke extendedMethod()
within the extension class. Therefore, one would expect the script to produce the following:
$this is set. Local value = hello. Base value = foobar $this is set. Local value = hello. Base value = foobar
However, because user_call_func_array
isn't propagating $this
correctly, I'm getting the following in PHP 5.3.4 on Mac OS X:
$this is set. Local value = hello. Base value = foobar $this is not set. Boo!
Can anyone shed some light on this or offer an alternative solution to my problem?
Thanks.
It is natural if $this
is not set in second call
$this
denotes the current object of class but in your case the class itself is calling the method hence $this
is not set.
class::method(); //The class itself is calling the method hence $this will be unset
Object->method();//$this will be set in this case because object is calling the method
精彩评论