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

时间:2016-08-27 14:37:13

标签: php closures

我有这样的代码:

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

2 个答案:

答案 0 :(得分:3)

您不能使用print sess.run([x[[0, 1, 2], [2,1,0]]])[0] ,因为这是对类实例本身的类内部的显式保留变量。复制到$this,然后将其传递给$this语言构造。

use

答案 1 :(得分:1)

将$ this给另一个var并使用它。

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