douhanxujiuji6098 2016-06-20 02:35
浏览 65
已采纳

PHP垃圾在调用返回后收集函数范围的对象吗?

I know that once a script ends, all objects are destroyed and memory is returned. Does this also happen to function-scoped objects once the function ends that aren't accessible anyway?

For instance, I'm worried about memory leaks in my PHPUnit tests, wherein I create a new object for almost every test. Will this eventually overflow my heap if I run enough tests?

public function testMyFunction()
{
    // Arrange
    $myObject = new MyClass();

    // Act
    $return = $myObject->myFunction();

    // Assert
    $this->assertEquals(true, $return);

}

Should I be manually unsetting them for long-running scripts in an "Absterge" section?

public function testMyFunction()
{
    // Arrange
    $myObject = new MyClass();

    // Act
    $return = $myObject->myFunction();

    // Assert
    $this->assertEquals(true, $return);

    // Absterge
    unset($myObject);
}
  • 写回答

1条回答 默认 最新

  • douyan6958 2016-06-20 02:59
    关注

    PHP will garbage collect once all references to an object are gone.

    unset is not needed. However, it is possible that you have a circular dependency, in which case it might not get garbage collected.

    The only reason for using unset() is if you'd like to free memory before the end of the function. If there's still something else holding a reference to the thing that you're unsetting, unset() only removes the local variable, but not the object itself.

    There's a special garbage collection cycle that cleans up as well circular references. You can control this with this php.ini setting:

    http://ca2.php.net/manual/en/info.configuration.php#ini.zend.enable-gc

    If you are interested in testing when and if your objects get garbage collected, you could add a __destruct method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?