Home » Php » php – How to access parent object from lambda functions?

php – How to access parent object from lambda functions?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a recursive lambda function in one of my objects, and it needs to access the object’s mysqli connection. This attempt

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

Produced an unreasonable fatal error

Fatal error: Cannot use $this as lexical variable in C:\Users\Codemonkey1991\Desktop\workspace\melior\objects\databasemanager.php on line 88

Could anyone give me a few pointers?


Edit: Just to clarify context, I’m trying to create this lambda function inside another function.

How to&Answers:

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

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

Answer:

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!'