title: PHP: Memory leak in recursive function
body: <p>I have a recursive function which, given an id, builds up a directory path.
  The thing is, it doesn't free up the space, so starting with a memory consumption of 15MB after 1761 folders, the memory consumption is at about 150MB which is not healthy.</p>
  
  <p>this is the function: </p>
  
  <pre><code>private function buildDirectoryPath($iId, $sDir = "") 
  {    
      $oFolder = Folders::getFolder($iId);
  
      if (!empty($sDir)) $sDir = $oFolder-&gt;getName() . "/" . $sDir;
          else $sDir = $oFolder-&gt;getName(). $sDir;
  
      if ($oFolder-&gt;getParentId() &gt; 0)
          $sDir = $this-&gt;buildDirectoryPath($oFolder-&gt;getParentId(), $sDir);
  
      return $sDir;
  }
  </code></pre>
  
  <p>and this is how i call it (inside the loop of the folders): </p>
  
  <pre><code>foreach ($aFolders as $aFolder) {           
      $sFolderPath = $this-&gt;buildDirectoryPath($aFolder["fol_id"]);
  }
  </code></pre>
  
  <p>so to be honest, i haven't written many recursive functions yet, so i am open to any adjustments</p>
  
  <p>edit, adding the Folders::getFolder static method:</p>
  
  <pre><code>static public function getFolders($sAppCode,
                                        $iParentId = 0)
      {
  
          $oDb = Zend_Registry::get('db');
          $oSelect = $oDb
              -&gt;select()
              -&gt;from('folders')
              -&gt;where('folders.fol_deleted_user_id = 0')
              -&gt;order('folders.fol_name ASC');
  
  
          if ($iParentId &gt;= 0) {
              $oSelect-&gt;where('folders.fol_parent_id = ' . (int)$iParentId);
          }
  
          $aFolders = $oDb-&gt;fetchAll($oSelect);
  
  //added the $object = null later
  
          $oDb = null;
          $oSelect = null;
          $oAppSelector = null;
          return $aFolders;
      }
  </code></pre>
  
  <p>edit2: if i won't find an easy solution, my plan b would be to put cache the paths, so i don't need to build them everything. its just that i have to alter a lot of code inside the app</p>