Yes, that is indeed correct.
The only way to call bar
is:
$bar = $foo->bar;
$bar();
Sad, but true.
Also worth noting, because of this same effect, there is no $this
inside $bar call (unless you pass it as function argument named as $this
).
Edit: As nikic pointed out, the value of $this
inside the closure is the same value of the scope of when the closure was created.
This may mean that $this
might be undefined on two occasions: when the scope was the global PHP scope or when the scope was from a static context. This, however, means that you can in theory feed the correct instance:
class Foo {
public $prop = 'hi';
function test(){
$this->bar = function(){
echo $this->prop;
}
$bar = $this->bar;
$bar();
}
}
$foo = new Foo();
$foo->test();
Also, it seems that with some class magic, you can achieve $this->bar()
as well:
class Foo {
// ... other stuff from above ...
public function __call($name, $args){
$closure = $this->$name;
call_user_func_array( $closure, $args ); // *
}
}
[*] Beware that call_user_func_array
is very slow.
Oh, and this is strictly for PHP 5.4 only. Before that, there's no $this
in closures :)
Also, you can see it in action here.