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

如何在php闭包中使用$this?,php,closures,Php,Closures,我有这样的代码: class Foo { var $callbacks = array(); function __construct() { $this->callbacks[] = function($arg) { return $this->bar($arg); }; } function bar($arg) { return $arg * $arg; } } 我想在闭包中使用$this,我尝

我有这样的代码:

class Foo {
   var $callbacks = array();
   function __construct() {
      $this->callbacks[] = function($arg) {
         return $this->bar($arg);
      };
   }
   function bar($arg) {
      return $arg * $arg;
   }
}
我想在闭包中使用$this,我尝试添加
use($this)
,但是这个抛出错误:

Cannot use $this as lexical variable

将$this赋予另一个var并使用它

class Foo
{
    public function bar()
    {
        $another = $this;
        return function() use($another)
        {
            print_r($another);
        };
    }
}

将$this赋予另一个var并使用它

class Foo
{
    public function bar()
    {
        $another = $this;
        return function() use($another)
        {
            print_r($another);
        };
    }
}

不能使用
$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;
   }
}

不能使用
$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;
   }
}

您使用的是哪个PHP版本?它是
5.3
还是更低版本?您使用的是哪个PHP版本?是
5.3
还是更低?