I would like to be able to call a closure that I assign to an object's property directly without reassigning the closure to a variable and then calling it. Is this possible?
The code below doesn't work and causes Fatal error: Call to undefined method stdClass::callback()
.
$obj = new stdClass();
$obj->callback = function() {
print "HelloWorld!";
};
$obj->callback();
Here is another way to successfully call object properties as closure.
When you don't want to change core object use this :
UPDATE:
I know this is old, but I think Traits nicely handle this problem if you are using PHP 5.4+
First, create a trait that makes properties callable:
Then, you can use that trait in your classes:
Now, you can define properties via anonymous functions and call them directly:
As of PHP7, you can do
or use Closure::call(), though that doesn't work on a
StdClass
.Before PHP7, you'd have to implement the magic
__call
method to intercept the call and invoke the callback (which is not possible forStdClass
of course, because you cannot add the__call
method)Note that you cannot do
in the
__call
body, because this would trigger__call
in an infinite loop.If you're using PHP 5.4 or above you could bind a callable to the scope of your object to invoke custom behavior. So for example if you were to have the following set up..
And you were operating on a class like so..
You could run your own logic as if you were operating from within the scope of your object
It seems to be possible using
call_user_func()
.not elegant, though.... What @Gordon says is probably the only way to go.