|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2018-02-04 14:04 UTC] john357smith at gmail dot com
 Description:
------------
In case an anonymous function is assigned to the class variable (doesn't matter if public, private or protected) and a new class instance is created a memory is not freed at the end. To correctly free memory you have to set a class variable to null or call a garbage collector manually. See test script.
Test script:
---------------
class TestMem
{
  public $class_var = null;
  public function __construct()
  {
    $this->class_var = function() { };
  }
}
while (true)
{
  $frame = new TestMem();
  //$frame->class_var = null;
  //echo(gc_collect_cycles()."\n");
  echo(memory_get_usage()."\n");
  usleep(10000);
}
Expected result:
----------------
A memory usage is still on the same level.
Actual result:
--------------
A memory usage is constantly increasing.
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 22:00:01 2025 UTC | 
The closure contains an implicit reference to $this. You can avoid creating the cycle by using a static closure: $this->class_var = static function() { }; Of course, this will only work if your closure does not require access to $this.