将对象属性传递到PHP的闭包中 [英] Passing an object property into a closure in PHP

查看:102
本文介绍了将对象属性传递到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){
      ...
    }
  }
}

$ events属性在 loopView()方法中实例化。似乎应该对我有用,但出现此错误:

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 ...

中期望','或')'没想到在 use 中有引用的对象。我不知道为什么这是无效的,经过一番谷歌搜索之后,我找不到任何引用我的具体问题。

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.

在PHP 7.1.7中,是否可以这样做,如果可以,正确的语法是什么?

In PHP 7.1.7, is it possible to do this, and if so, what is the correct syntax?

推荐答案

您只需在闭包中使用 $ this->事件即可,而无需 use 语句。

You can just use $this->events in the closure without a use statement.

请参见 $ this 的自动绑定 href = http://php.net/manual/en/fu nctions.anonymous.php rel = noreferrer>匿名函数文档

See "Automatic Binding of $this" in the anonymous function documentation.


从PHP 5.4.0开始,当在类的上下文中声明时,当前类将自动绑定到它,从而使$ 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.

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

至于解析错误的原因,如果我们忽略特定的 $ this 情况,

As far as the reason for the parse error, if we disregard the specific $this case,

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

不起作用,因为 use 变量从父范围传递到闭包中,并且

$ object->属性不是变量,而是一个表达式。

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.

如果需要在闭包内引用对象属性,则需要使用整个对象,或将属性分配给anothe您可以使用的r变量。但是在这种情况下,您不必担心,因为 $ this 很特殊。

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.

这篇关于将对象属性传递到PHP的闭包中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆