Am I missing something or do closures simply not work as class methods? Take this for instance:
$foo = new stdClass();
$foo->bar = function() {
echo '@@@';
};
$foo->bar();
Seems to give me an error of “Fatal error: Call to undefined method stdClass::bar() in /blah/blah.php on line X”
Shouldn’t this instead invoke the closure that was placed in the “bar” property?
Yes, that is indeed correct.
The only way to call
baris:Sad, but true.
Also worth noting, because of this same effect, there is no$thisinside $bar call (unless you pass it as function argument named as$this).Edit: As nikic pointed out, the value of
$thisinside the closure is the same value of the scope of when the closure was created.This may mean that
$thismight 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:Also, it seems that with some class magic, you can achieve
$this->bar()as well:[*] Beware that
call_user_func_arrayis very slow.Oh, and this is strictly for PHP 5.4 only. Before that, there’s no
$thisin closures 🙂Also, you can see it in action here.