| 
        php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
  [2005-07-06 23:44 UTC] rodricg at sellingsource dot com
 Description:
------------
Objects with recursive references leak memory. 
PHP 5.1.0b2 exhibits the same behavior. 
Reproduce code:
---------------
<?php
class A {
    function __construct () {
        $this->b = new B($this);
    }
}
class B {
    function __construct ($parent = NULL) {
        $this->parent = $parent;
    }
}
for ($i = 0 ; $i < 1000000 ; $i++) {
    $a = new A();
}
?>
Expected result:
----------------
Memory usage should remain constant. 
Actual result:
--------------
Memory usage quickly increases to consume several hundred 
megabytes. 
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             
             | 
    |||||||||||||||||||||||||||||||||||||
            
                 
                Copyright © 2001-2025 The PHP GroupAll rights reserved.  | 
        Last updated: Tue Nov 04 11:00:01 2025 UTC | 
You can avoid the memory leak by manually calling the destructors and unsetting the recursive ref: <?php class A { function __construct () { $this->b = new B($this); } function __destruct () { $this->b->__destruct(); } } class B { function __construct ($parent = NULL) { $this->parent = $parent; } function __destruct () { unset($this->parent); } } for ($i = 0 ; $i < 1000000 ; $i++) { $a = new A(); $a->__destruct(); } echo number_format(memory_get_usage()); ?>Maybe solutution can be to call destructor every time when new object is assigned to old reference? Example: <?php class A { function __construct () { $this->b = new B($this); } function __destruct () { $this->b->__destruct(); } } class B { function __construct ($parent = NULL) { $this->parent = $parent; } function __destruct () { unset($this->parent); } } for ($i = 0 ; $i < 1000000 ; $i++) { $a = new A(); $a->__destruct(); } echo number_format(memory_get_usage()); ?> $a->__destruct(); can be called automatically because new reference is created. Then writing correct destructors will solve this issue. Or maybe I missing something?<?php class A { function __construct () { $this->b = new B($this); } } class B { function __construct ($parent = NULL) { $this->parent = $parent; } } for ($i = 0 ; $i < 1000000 ; $i++) { $a = new A(); unset($a); } echo number_format(memory_get_usage()); ?> Try this code. you will also avoid the memory leak... This forum really helps me to solve this problem. You gave me an idea to avoid this bugs. i really appreciate it. Thanks a lot guys.