I am new to OOP in PHP (normally write software). I have read that when an object goes out of scope it will be free’d so there is no need to do it manually. However, if I have a script like:
while ($var == 1) {
$class = new My_Class();
//Do something
if ($something) {
break;
}
}
This script will loop until $something is true which in my mind will create a lot of instances of $class. Do I need to free it at the end of each iteration? Will the same var name just re-reference itself? If I do need to free it, would unset() suffice?
Thanks.
When you assign a new instance to a variable, the old instance referenced by that variable (if any) has its reference count decreased. In this case the refcount will become zero. Since it is no longer referenced it will be automatically cleaned up.
From PHP 5.3 there is a proper garbage collector that can also handle circular references. You can enable it by calling
gc_enable.