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.
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!'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With