opis/closure

Error when use $this only in inside closure

Closed this issue · 1 comments

Code Example

class OneObject
{
    protected $id = 123;

    public function main()
    {
        $closure = new SerializableClosure(function () {
            // $this; // open this comment can resolve this problem
            return function () {
                var_dump($this->id);
            };
        });

        $rebuildClosure = unserialize(serialize($closure));

        $rebuildClosure()();
    }
}

(new OneObject())->main();

Result

PHP Fatal error:  Uncaught Error: Using $this when not in object context in closure://function () {
            // $this; // open this comment can resolve this problem
            return function () {
                \var_dump($this->id);
            };
        }:5

We know about this, and I'm very sure that version 3.x will not have a fix this.
The trick with $this; will do the job without affecting the execution.