How to access parent object from lambda functions? How to access parent object from lambda functions? php php

How to access parent object from lambda functions?


Because closures are themselves objects, you need to assign $this to a local variable, like:

$host = $this;$recfunc = function($id, $name) use ($host) { ...


The reference to $this does not need to be explicitly passed to the lambda function.

class Foo {    public $var = '';    public function bar() {        $func = function() {            echo $this->var;        };        $func();    }}$foo = new Foo();$foo->var = 'It works!';$foo->bar(); // will echo 'It works!'