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?
Tomaka17
source share