title: Can I trigger PHP garbage collection to happen automatically if I have circular references?
body: <p>I seem to recall a way to setup the <code>__destruct</code> for a class in such a way that it would ensure that circular references would be cleaned up as soon as the outside object falls out of scope. However, the simple test I built seems to indicate that this is not behaving as I had expected/hoped.</p>
  
  <p>Is there a way to setup my classes in such a way that PHP would clean them up correctly when the outermost object falls out of scope?</p>
  
  <p>I am not looking for alternate ways to write this code, I am looking for whether or not this can be done, and if so, how? I generally try to avoid these types of circular references where possible.</p>
  
  <pre><code>class Bar {
      private $foo;
      public function __construct($foo) {
          $this-&gt;foo = $foo;
      }
      public function __destruct() {
          print "[destroying bar]\n";
          unset($this-&gt;foo);
      }
  }
  
  class Foo {
      private $bar;
      public function __construct() {
          $this-&gt;bar = new Bar($this);
      }
      public function __destruct() {
          print "[destroying foo]\n";
          unset($this-&gt;bar);
      }
  }
  
  function testGarbageCollection() {
      $foo = new Foo();
  }
  
  for ( $i = 0; $i &lt; 25; $i++ ) {
      echo memory_get_usage() . "\n";
      testGarbageCollection();
  }
  </code></pre>
  
  <p>The output looks like this:</p>
  
  <pre><code>60440
  61504
  62036
  62564
  63092
  63620
   [ destroying foo ]
   [ destroying bar ]
   [ destroying foo ]
   [ destroying bar ]
   [ destroying foo ]
   [ destroying bar ]
   [ destroying foo ]
   [ destroying bar ]
   [ destroying foo ]
   [ destroying bar ]
  </code></pre>
  
  <p>What I had hoped for:</p>
  
  <pre><code>60440
   [ destorying foo ]
   [ destorying bar ]
  60440
   [ destorying foo ]
   [ destorying bar ]
  60440
   [ destorying foo ]
   [ destorying bar ]
  60440
   [ destorying foo ]
   [ destorying bar ]
  60440
   [ destorying foo ]
   [ destorying bar ]
  60440
   [ destorying foo ]
   [ destorying bar ]
  </code></pre>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>There are several great answers to this question relating to PHP > 5.3, but I selected the answer that would work with PHP &lt; 5.3 since it actually relates to my project ( PHP 5.2.x ).</p>