Have $this in PHP implicit function before PHP 5.4.0
According to http://php.net/manual/en/functions.anonymous.php, in PHP 5.3 $this
is not accessible from inside an implicit function, even if the function is defined in a context where $this
exists. Is there any way to work around this limitation? (by the way, upgrading the PHP installation on the webserver is not possible)
The way I would like to use the implicit function is to define a callback which is a member function of some object. More precisely, I would like to do something like
$callback = function() { return $this->my_callback(); }
Actually, an event better syntax would be
$callback = $this->my_callback
but I cannot make it work (PHP dies with "Fatal error: Function name must be a string" when I try to execute the callback).
Should do the work:
$object = $this ;
$callback = function() use ($object) { return $object->my_callback(); } ;
use
will bring an accessible variable (in our case the reference of the object) upon its declaration to the function scope, so you will not have to send it as a parameter.
Sometimes it is even better to use such a varname as $self
or $that
so to be more clear.
$function = array($this, 'my_callback');
(可能与call_user_func()
结合)
It looks like you can pass variables to the callback function. I haven't worked with closures in PHP, but I think this would work for you:
$callback = function($instance) { return $instance->my_callback(); }
$callback($this);
Or if the callback is triggered outside the current class.
$callback($myClassInstance);
链接地址: http://www.djcxy.com/p/59146.html
上一篇: 在PHP中整数检查