Hubro Hubro - 2 years ago 80
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.

Answer Source

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

$host = $this;
$recfunc = function($id, $name) use ($host) { ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download