PHP: unset() not freeing memory fully on objects

I spent a while trying to figure this out; but it’s quite simple (though I find rather counter-intuitive). Essentially when you create an object in PHP you are allocating memory to that object. When you want to remove that object you can use the unset() function (just like on most things in PHP). The problem occurs when there are variables stored inside the object — unset() doesn’t delete these from memory. This is because unset() doesn’t trigger the object’s destructor. A simple way around it is to explicitly call the destructor and then unset the object like so:

$myobject = new CrazySystem();
$myobject->LargeVariable = file_get_contents("VeryLargeFile.txt");
//Now we want to delete the object and everything it contains
$myobject->__destruct();
unset($myobject);
//It's now all gone!

Hope that helps anyone who was wondering why unsetting object still wasn’t freeing memory!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>