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();
You can assign
$thisto some variable and then useusekeyword 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:It is worth noting that
$objwill be seen as standard object (rather than as$this), so you won’t be able to access private and protected members.