Freeing objects in PHP

I am new to OOP in PHP (I usually write a program). I read that when an object goes out of scope, it will be free, 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 opinion will create many instances of $class . Do I need to free it at the end of each iteration? Will the same var name just re-refer to itself? If I need to free it, is unset() enough?

Thanks.

+4
source share
3 answers

When you assign a new instance to a variable, the old instance referenced by that variable (if any) has a number of references . In this case, refcount will become zero. Since it is no longer referenced, it will be automatically cleared.

From PHP 5.3, there is a proper garbage collector that can also handle circular references. You can enable it by calling gc_enable .

+3
source

In this context, unset() should not be necessary, as it will be overwritten at each iteration of the loop. Depending on what other actions happen in the while , it may be preferable to assign $class outside the loop. Does $class at every iteration?

 $class = new My_Class(); while ($var ==1) { // Do something } 
+2
source

If: the cycle will work for a very long time; you expect a large number of concurrent users; or the server has limited resources (for example, the host itself, VPS / shared, etc.), then you do not need to worry about it. In any case, when the script will not work for a very long time (less than 5 seconds), everything you try to do to free memory will be less efficient than the PHP garbage collector.

However, if you need to clear the link (due to one of the above scenarios or because you like being careful), you can set the variable to null or use the unset function. This will remove the link, and the PHP garbage collector will clear it because there are no more links to it.

+2
source

Source: https://habr.com/ru/post/1340868/


All Articles