类上下文中的call_user_func(定义了$ this)

rom*_*nsh 5 php

有没有办法如何在对象的上下文中执行PHP5.3中的闭包?

class Test {
    public $name='John';

    function greet(){
        eval('echo "Hello, ".$this->name;');

        call_user_func(function(){
            echo "Goodbye, ".$this->name;
        });
    }
}
$c = new Test;
$c->greet();
Run Code Online (Sandbox Code Playgroud)

eval()可以正常工作,但是call_user_func将无法访问$ this.(在不在对象上下文中时使用$ this).我现在正在通过"$ this"作为关闭的论据,但这并不是我所需要的.

Gor*_*don 6

$this从PHP 5.3.6开始,无法从lambda或闭包访问.您必须分配$this给临时变量并使用它use(这意味着您只能使用公共API)或传入/使用所需的属性.所有这些都显示在本网站的其他地方,所以我不会重申.

访问$this是在树干可尽管对于PHP.next:http://codepad.viper-7.com/PpBXa2