$this in closures; what gives?
This article (among others) states that it is possible to use the $this variable in a closure defined in a class method even without importing it via use(). I also read the RFC from the PHP wiki and it says the same thing. Why then does this code fail?
class foo
{
public $bat;
public function __construct($bat)
{
$this->bat = $bat;
}
public function bar()
{
return function() {
return $this->bat;
};
}
public function baz()
{
return $this->bar();
}
}
Using 5.3RC1/win32, it dies when bar() is called outside or inside (via baz()) the class, saying $this is used in a non-object context. It doesn’t allow ... function() use($this) { ... either, saying that $this cannot be used as a lexical variable. What’s happening?
To work around this, right now I’m assigning $this to $self above the closure definition and appending use($self). Seems to work as expected, except that I can’t access private members (which is probably intentional and exactly the thing I was exploring when I made this test). Why can’t I just import $this directly then? And whatever happened to the auto-import they promised?
Update: Man, I totally missed this. This page is linked in the closure RFC. They should have removed that entire section in the RFC instead, like they did to the lexical keyword (I can’t seem to find it anymore, or maybe I just imagined it). I just skimmed through it (since I’ve read it before) and missed the link entirely. So $this really cannot be imported at the moment, but it appears that they might be in the future.