Sometimes you’ll need to clean up the memory used by PHP. Especially if you have long running CLI scripts this will make sure to avoid the “PHP Fatal error: Allowed memory size of N bytes exhausted”. The basic idea is to remove unused variables from memory by using PHP’s unset() command.
In it’s simpliest form, unset() will look like this:
<?php php $i = "is now set"; echo $i; unset($i); // remove $i from memory, i.e. tell the garbage collector that it may unallocate $i ?>
Internally, PHP works more or less like Java when it comes to unsetting variables. Thus, unset() will not immediately unset the corresponding variable. Instead, it simply tells it’s garbage collector that the variable is no longer needed and may now be removed from memory. Good news are that the garbage collector now works quite smart and usually you don’t have to take care of how it works. Bad news are, that there are still some cases when the garbage collector fails. Continue Reading…