Is there a way to NOT write $ this in an anonymous PHP function?

I have a PHP code that looks like this:

class A { public function __construct() { $this->b = new B(function($x) { return $x + 1; }); } }; class B { public function __construct($dataProcessingFunction) { $this->dataProcessingFunction = $dataProcessingFunction; } public function processData($data) { $f = $this->dataProcessingFunction; return $f($data); } }; 

But there is a problem: I absolutely need the destructor B to be called before the destructor. It seems reasonable, as you can see. Object B does not require any A, so there should be no problem.

But with PHP 5.4.0, closing seems to automatically commit $ this implicitly. Therefore, the lambda function that I pass to B and which is stored in B contains a reference to A.

This means that A contains a pointer to B, and B contains a pointer to A (via closure). In a similar situation, the PHP documentation says that destructors are called only when garbage collection and in random order. And guess what: B the destructor is always called before A.

Is there any way to solve this in an elegant way?

+7
source share
1 answer

Thanks to Explosion Pills, I found a solution in the Closure class.

In fact, you can change the $this stored inside the closure, for example:

 $cb = function($x) { return $x + 1; }; $cb = $cb->bindTo(null); // now $cb doesn't contain a pointer to $this anymore 

Note that you cannot do this, or you will get a syntax error:

 // syntax error $cb = (function($x) { return $x + 1; })->bindTo(null); 
+4
source

All Articles