4

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);
}
Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167

1 Answers1

4

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:

https://www.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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Evert
  • 93,428
  • 18
  • 118
  • 189
  • sorry it took me so long to circle back to testing your answer. using the `__destruct` method to test was the obvious insight I'd missed. thanks!! – Jeff Puckett Jul 01 '16 at 14:09