Giovanni Mascellani
Giovanni Mascellani

Reputation: 1278

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).

Upvotes: 3

Views: 620

Answers (3)

sybear
sybear

Reputation: 7784

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.

Upvotes: 4

Patrick M
Patrick M

Reputation: 10989

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);

Upvotes: 0

faffaffaff
faffaffaff

Reputation: 3549

$function = array($this, 'my_callback');

(perhaps combined with call_user_func() )

Upvotes: 1

Related Questions