Passing an object property into a closure in PHP

只谈情不闲聊 提交于 2019-12-02 00:24:11

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!