如何从lambda函数访问父对象?

Hub*_*bro 33 php lambda closures class function

我的一个对象中有一个递归的lambda函数,它需要访问对象的mysqli连接.这种尝试

$recfunc = function($id, $name) use($this) {
Run Code Online (Sandbox Code Playgroud)

产生了不合理的致命错误

致命错误:不能在第88行的C:\ Users\Codemonkey1991\Desktop\workspace\melior\objects\databasemanager.php中使用$ this作为词法变量

谁能给我一些指示?


编辑:只是为了澄清上下文,我试图在另一个函数中创建这个lambda函数.

Lon*_*ars 50

因为闭包本身就是对象,所以需要分配$this一个局部变量,如:

$host = $this;
$recfunc = function($id, $name) use ($host) { ...
Run Code Online (Sandbox Code Playgroud)

  • `$ recfunc = function($ id,$ name)use($ host,&$ recfunc){if(FOO)return $ recfunc($ id,$ name); }` (4认同)
  • 通过检查有关此错误的bugs.php.net报告,此功能已添加到PHP 5.4中. (3认同)

Sip*_*hon 5

对 的引用$this不需要显式传递给 lambda 函数。

class Foo {
    public $var = '';

    public function bar() {
        $func = function() {
            echo $this->var;
        };
        $func();
    }
}

$foo = new Foo();
$foo->var = 'It works!';
$foo->bar(); // will echo 'It works!'
Run Code Online (Sandbox Code Playgroud)