Reputation: 18046
I am trying to pass an object property into a closure (that's within a method of that object), like so:
class Entity extends ControllerBase {
private $view;
private $events;
public function print($tid) {
self::loadView($tid);
self::loopView();
return (new StreamedResponse(function() use ($this->events){
...
}
}
}
The $events property gets instantiated in the loopView()
method. This seems like it should work to me, but I get this error:
ParseError: syntax error, unexpected '->' (T_OBJECT_OPERATOR), expecting ',' or ')' in ...
It seems to be saying it doesn't expect there to be an object referenced in use
. I don't know why this isn't valid, and after some googling, I couldn't find anything referencing my specific problem.
In PHP 7.1.7, is it possible to do this, and if so, what is the correct syntax?
Upvotes: 3
Views: 2340
Reputation: 41810
You can just use $this->events
in the closure without a use
statement.
See "Automatic Binding of $this
" in the anonymous function documentation.
As of PHP 5.4.0, when declared in the context of a class, the current class is automatically bound to it, making $this available inside of the function's scope.
For example: https://3v4l.org/gYdHp
As far as the reason for the parse error, if we disregard the specific $this
case,
function() use ($object->property) { ...
doesn't work because use
passes variables from the parent scope into the closure, and
$object->property
is not a variable, it is an expression.
If you need to refer to an object property inside a closure, you either need to use
the entire object, or assign the property to another variable you can use
. But in this case you don't have to worry about that since $this
is special.
Upvotes: 16