Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent object from lambda functions?

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.

like image 389
Hubro Avatar asked Mar 04 '11 01:03

Hubro


2 Answers

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

$host = $this;
$recfunc = function($id, $name) use ($host) { ...
like image 185
Long Ears Avatar answered Nov 03 '22 05:11

Long Ears


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!'
like image 25
Siphon Avatar answered Nov 03 '22 05:11

Siphon