class MyClass {
var $lambda;
function __construct() {
$this->lambda = function() {echo 'hello world';};
// no errors here, so I assume that this is legal
}
}
$myInstance = new MyClass();
$myInstance->lambda();
//Fatal error: Call to undefined method MyClass::lambda()
So what is the correct syntax for reaching class variables ?
You can also call your lambda function without change something in your class, using ReflectionFunction.
or if you have to pass arguments then
In PHP, methods and properties are in a separate namespace (you can have a method and a property with the same name), and whether you are accessing a property or a method depends of the syntax you are using to do so.
$expr->something()
is a method call, so PHP will searchsomething
in the class' list of methods.$expr->something
is a property fetch, so PHP will searchsomething
in the class' list of properties.$myInstance->lambda();
is parsed as a method call, so PHP searches for a method namedlambda
in your class, but there is no such method (hence the Call to undefined method error).So you have to use the fetch property syntax to fetch the lambda, and then call it.
Since PHP 7.0, you can do this with
($obj->lambda)()
:The parentheses make sure that PHP parses
($obj->lambda)
as fetch the property named lambda. Then,()
calls the result of fetching the property.or you can do this with
->lambda->__invoke()
:__invoke
is one of PHP's magic methods. When an object implements this method, it becomes invokable: it can be called using the$var()
syntax. Anonymous functions are instances ofClosure
, which implements__invoke
.Or assign it to a local variable:
Or call it using call_user_func:
call_user_func
can call anycallable
, including anonymous functions.Alternatively, if this is a common pattern in your code, you can setup a
__call
method to forward calls to your lambda:Now this works:
Since PHP 5.4 you can even do that in a trait: