Why can I not use $this as a lexical variable in PHP 5.5.4?

The issue is that including $this in the use() statement is not allowed.

However if you don't include it then it will work fine.

So the issue isn't whether the use statement is present, it's whether $this is present in the use statement.

This should work (@see https://3v4l.org/smvPt):

class Foo{
    private $a;
    function getAnon(){
        $b = 1;
        return function() use ($b) { 
            echo $b;
            echo $this->a;
        };
    }
}

This shouldn't:

class Foo{
    private $a;
    function getAnon(){
        $b = 1;
        return function() use ($this, $b) { 
            echo $b;
            echo $this->a;
        };    
    }
}

I suppose essentially $this is implicitly captured.


In PHP 5.3 if you are using a Closure inside of a class, the Closure will not have access to $this.

In PHP 5.4, support has been added for the usage of $this in Closures.


I don't know the answer to your actual question (ie Why can't you do it), but I can give you a work around: Use a temporary copy of $this and use() that instead:

class Foo
{
    public function bar()
    {
        $that = $this;
        return function() use($that)
        {
            print_r($that);
        };
    }
}

I've just tested it, and this does work.


So it seems $this can be used simply if it isn't specified via the "use" keyword.

The following echoes 'bar':

class Foo
{
    private $foo = 'bar';

    public function bar()
    {
        return function()
        {
            echo $this->foo;
        };
    }
}

$bar = (new Foo)->bar();

$bar();

This was reported in the php-internals mailing list and is apparently overhang from 5.3's lack of support for this functionality:

http://marc.info/?l=php-internals&m=132592886711725

Tags:

Php