这个 PHP 脚本会泄漏内存吗?

Will this PHP script leak memory?

我有一个 PHP 脚本在后台运行了一段时间(通常是几分钟,但也可能长达一个小时左右)。它包含一个循环,我需要在其中创建一个对象。我目前每次都使用相同的名称,如下所示:

while (!$job_finished) {
    $x = new MyClass();
    $x->doStuff();
    $x->doMoreStuff();
    unset ($x);

    // more code here
}

由于我用相同的名称重复创建 $x,垃圾回收会正确地清理内存吗?或者我应该在 $x 上使用数组,例如

   $x[$i] = new MyClass();

是的,如果您保留对数组的对象引用,它不会释放内存并且最后会失败。

但是,您显示的代码示例不会出现内存问题,因为您没有保留对象的引用并始终在循环中覆盖它。

其实我不需要用数组。 unset() 命令会破坏对象,因此我不必担心。这是在 PHP documentation 中,它指出:

The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

我用下面的代码测试了它,它确实显示了在脚本结束之前调用的 destruct 方法。

<?php

class A {
  function __destruct() {
    echo "cYa later!!\n";
  }
}

$a = new A();
unset($a);

echo "hello";
sleep(10);