Passing an object property into a closure in PHP

半腔热情 提交于 2019-12-04 04:59:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/54600737/passing-an-object-property-into-a-closure-in-php

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