How to pass object context to an anonymous functio

2019-06-16 06:55发布

问题:

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.