简体   繁体   English

将对象属性传递给PHP的闭包

[英]Passing an object property into a closure in PHP

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. $ events属性在loopView()方法中实例化。 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 . 似乎是在说它不期望有一个引用的对象在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? 在PHP 7.1.7中,可以这样做,如果可以,正确的语法是什么?

You can just use $this->events in the closure without a use statement. 您可以只在闭包中使用$this->events而不use语句。

See "Automatic Binding of $this " in the anonymous function documentation . 请参阅匿名函数文档$this自动绑定”。

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. 从PHP 5.4.0开始,在类的上下文中声明时,当前类会自动绑定到它,从而使$ this在函数的作用域内可用。

For example: https://3v4l.org/gYdHp 例如: https//3v4l.org/gYdHp


As far as the reason for the parse error, if we disregard the specific $this case, 至于解析错误的原因,如果我们忽略特定的$this情况,

function() use ($object->property) { ...

doesn't work because use passes variables from the parent scope into the closure, and 不起作用,因为use变量从父范围传递到闭包中,并且
$object->property is not a variable, it is an expression. $object->property不是变量,它是一个表达式。

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 . 如果需要在闭包内部引用对象属性,则需要use整个对象,或者将该属性分配给可以use另一个变量。 But in this case you don't have to worry about that since $this is special. 但是在这种情况下,您不必担心,因为$this很特殊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM