Reputation: 15934
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.
Upvotes: 4
Views: 763
Reputation: 838156
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
.
Upvotes: 3
Reputation: 50592
Unless: the loop will be running a very long time; you anticipate a high number of concurrent users; or there are limited resources on the server (i.e. self-host, VPS/shared, etc), then you don't need to worry about it. In any scenario where the script won't be running for very long (less than 5 seconds), anything you try to do to free memory is going to be less effective than PHP's garbage collector.
That said, if you need to clear the reference (because of one of the aforementioned scenarios, or because you like to be tidy), you can set the variable to null or use the unset
function. That will remove the reference and PHP's garbage collector will clean it up because there are no more references to it.
Upvotes: 2
Reputation: 270607
It shouldn't be necessary to unset()
it in this context, as it will be overwritten on each iteration of the loop. Depending on what other actions are taking place in the while
loop, it may be preferable to assign the $class
outside the loop. Does $class
change on each iteration?
$class = new My_Class();
while ($var ==1)
{
// Do something
}
Upvotes: 2