如何在php闭包中使用$this?

jcu*_*bic 1 php closures

我有这样的代码:

class Foo {
   var $callbacks = array();
   function __construct() {
      $this->callbacks[] = function($arg) {
         return $this->bar($arg);
      };
   }
   function bar($arg) {
      return $arg * $arg;
   }
}
Run Code Online (Sandbox Code Playgroud)

我想在闭包中使用 $this ,我尝试添加use ($this)但是这个抛出错误:

Cannot use $this as lexical variable
Run Code Online (Sandbox Code Playgroud)

Cha*_*ois 5

您不能使用,$this因为这是类内部对类实例本身的引用的显式保留变量。制作一个副本$this,然后将其传递给use语言结构。

class Foo {
   var $callbacks = array();
   function __construct() {
      $class = $this;
      $this->callbacks[] = function($arg) use ($class) {
         return $class->bar($arg);
      };
   }
   function bar($arg) {
      return $arg * $arg;
   }
}
Run Code Online (Sandbox Code Playgroud)