我在 ArrayObject 中寻找 __destroy() 方法,但没有找到实现。如果我将包含 ArrayObject 的变量设置为 NULL,它会正确销毁存储在其中的所有对象并释放内存吗?或者我应该在取消设置之前迭代 ArrayObject 以销毁每个对象?
问问题
206 次
2 回答
2
在 PHP 中,您永远不必担心超出您自己范围的内存使用。unset($obj)
在你的情况下会正常工作。或者,您可以简单地离开您所在的功能:
function f() {
$obj = new ArrayObject();
// do something
}
并且数据将被清理得很好。
PHP 的内部内存管理相当简单:为每条数据保留一个引用计数,如果为 0,则将其释放。如果只有 ArrayObject 持有该对象,则它的 refcount 为 1。一旦 ArrayObject 消失,refcount 为 0,该对象将消失。
于 2011-11-26T15:40:49.900 回答
2
当您取消设置或为空 ArrayObject 时,只有 ArrayObject 实例被销毁。如果 ArrayObject 包含其他对象,只要没有从其他地方对它们的引用,这些对象就会被销毁,例如
$foo = new StdClass;
$ao = new ArrayObject;
$ao[] = $foo;
$ao[] = new StdClass;
$ao = null; // will destroy the ArrayObject and the second stdClass
var_dump($foo); // but not the stdClass assigned to $foo
另见http://www.php.net/manual/en/features.gc.refcounting-basics.php
于 2011-11-26T15:42:31.073 回答