如何将对象上下文传递给匿名函数? [英] How to pass object context to an anonymous function?

查看:31
本文介绍了如何将对象上下文传递给匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将对象上下文传递给匿名函数而无需将 $this 作为参数传递?

Is there a way of passing object context to an anonymous function without passing $this as an argument?

class Foo {
    function bar() {
        $this->baz = 2;
        # Fatal error: Using $this when not in object context
        $echo_baz = function() { echo $this->baz; };
        $echo_baz();
    }
}
$f = new Foo();
$f->bar();

推荐答案

您可以将 $this 赋值给某个变量,然后使用 use 关键字将该变量传递给函数,在定义函数时,虽然我不确定它是否更容易使用.无论如何,这是一个例子:

You can assign $this to some variable and then use use keyword to pass this variable to function, when defining function, though I'm not sure if it is easier to use. Anyway, here's an example:

class Foo {
    function bar() {
        $this->baz = 2;
        $obj = $this;
        $echo_baz = function() use($obj) { echo $obj->baz; };
        $echo_baz();
    }
}
$f = new Foo();
$f->bar();

值得注意的是,$obj 将被视为标准对象(而不是 $this),因此您将无法访问 private 和 protected会员.

It is worth noting that $obj will be seen as standard object (rather than as $this), so you won't be able to access private and protected members.

这篇关于如何将对象上下文传递给匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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