Hubro Hubro - 10 months ago 44
PHP Question

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.


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

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