我似乎记得一种设置__destruct
类的方法,它可以确保一旦外部对象超出范围,循环引用就会被清除。但是,我构建的简单测试似乎表明这并没有像我预期/希望的那样表现。
有没有办法设置我的类,当最外面的对象超出范围时,PHP 会正确清理它们?
我不是在寻找编写此代码的替代方法,而是在寻找是否可以这样做,如果可以,如何?我通常会尽可能避免这些类型的循环引用。
class Bar {
private $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __destruct() {
print "[destroying bar]\n";
unset($this->foo);
}
}
class Foo {
private $bar;
public function __construct() {
$this->bar = new Bar($this);
}
public function __destruct() {
print "[destroying foo]\n";
unset($this->bar);
}
}
function testGarbageCollection() {
$foo = new Foo();
}
for ( $i = 0; $i < 25; $i++ ) {
echo memory_get_usage() . "\n";
testGarbageCollection();
}
输出如下所示:
60440
61504
62036
62564
63092
63620
[ destroying foo ]
[ destroying bar ]
[ destroying foo ]
[ destroying bar ]
[ destroying foo ]
[ destroying bar ]
[ destroying foo ]
[ destroying bar ]
[ destroying foo ]
[ destroying bar ]
我所希望的:
60440
[ destorying foo ]
[ destorying bar ]
60440
[ destorying foo ]
[ destorying bar ]
60440
[ destorying foo ]
[ destorying bar ]
60440
[ destorying foo ]
[ destorying bar ]
60440
[ destorying foo ]
[ destorying bar ]
60440
[ destorying foo ]
[ destorying bar ]
更新:
这个与 PHP > 5.3 相关的问题有几个很好的答案,但我选择了适用于 PHP < 5.3 的答案,因为它实际上与我的项目( PHP 5.2.x )有关。