How to pass object context to an anonymous function?

荒凉一梦 提交于 2019-12-10 12:44:07

问题


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

回答1:


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

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.



来源:https://stackoverflow.com/questions/6330602/how-to-pass-object-context-to-an-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!