类上下文中的call_user_func(已定义$ this) [英] call_user_func within class context (with $this defined)

查看:101
本文介绍了类上下文中的call_user_func(已定义$ this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在对象上下文中在PHP5.3中执行闭包?

Is there a way how to execute closure in PHP5.3 within a context of an object?

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();

eval()可以正常工作,但是call_user_func将无法访问$ this. (在不在对象上下文中时使用$ this ). 我现在将"$ this"作为参数传递给闭包,但这并不是我真正需要的.

The eval() would work fine, however call_user_func will have no access to $this. (Using $this when not in object context). I am passing "$this" as an argument to closure right now, but that's not exactly what I need.

推荐答案

从PHP 5.3.6开始,无法通过lambda或闭包访问$this.您要么必须将$this分配给一个临时变量,然后将其与use一起使用(这意味着您将只有可用的公共API),要么传入/使用所需的属性.所有内容均显示在该网站的其他位置,因此我不再重复.

Access to $this is not possible from lambda or closure as of PHP 5.3.6. You'd either have to assign $this to a temp var and use that with use (which means you will only have the public API available) or pass in/use the desired property. All shown elsewhere on this site, so I won't reiterate.

虽然对PHP.next也可以在Trunk中访问$this: http://codepad.viper -7.com/PpBXa2

Access to $this is available in Trunk though for PHP.next: http://codepad.viper-7.com/PpBXa2

这篇关于类上下文中的call_user_func(已定义$ this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆