Is there a way NOT to capture $this in a PHP anonymous 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 B's destructor to be called before A's destructor. This seems reasonable as you can see. The B object doesn't need any A, so there should be no problem.

But since PHP 5.4.0, closures seem to automatically capture implicitly $this. Therefore, the lambda function that I pass to B and that is stored by B contains a reference to A.

Which means that A contains a pointer to B, and B contains a pointer to A (through the closure). In this kind of situation, the PHP documentation says that destructors are only called on garbage collection and in a random order. And guess what: B's destructor is always called before A's.

Is there a way to solve this in a elegant way?


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

You can in fact change the $this stored inside the closure, like this:

$cb = function($x) { return $x + 1; };
$cb = $cb->bindTo(null);

// now $cb doesn't contain a pointer to $this anymore

Note that you can't do this, or you'll get a syntax error:

// syntax error
$cb = (function($x) { return $x + 1; })->bindTo(null);
链接地址: http://www.djcxy.com/p/67208.html

上一篇: 零退出状态“错误下载XML和RCurl R软件包

下一篇: 有没有办法在PHP匿名函数中捕获$ this?