Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PHP NOT clear memory after leaving loops?

Tags:

php

for($i=0; $i<3; $i++) {
    echo '$i = ' . $i . '<br/>' ;
}
echo 'out of loop, $i = ' . $i;

the above outputs:

$i = 0
$i = 1
$i = 2
out of loop, $i = 3

It doesn't make sense to me that $i is still visible even after displaying it out of the loop scope. Why does this happen (in java it's automatically garbage-collected)?

And is there a way to tell php to automatically do garbage-collection after getting out of loop scope? My code looks ugly when I have to call unset() after each loop.

like image 892
evilReiko Avatar asked Feb 03 '11 09:02

evilReiko


3 Answers

This isn't about garbage collection, it's about scope.

In PHP, for loops do not create their own scope. $i is created in the same scope as the loop, so it still exists after the loop ends. It's not going to be garbage collected any more than a variable you declare on the line before the loop would be.

Think of it as a feature, as it's often used as one. For example, you don't have to declare your loop counter before the loop to know what its value was after breaking out of the loop.

If you do manually unset the variable, you can force garbage collection with gc_collect_cycles as of PHP 5.3.

like image 75
Dan Grossman Avatar answered Oct 15 '22 19:10

Dan Grossman


From Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. […] Within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope.

The variable will not be garbage collected because you still have a reference to $i in the scope after leaving the loop. Note that using unset will not do any garbage collection, but it will only mark memory no longer referenced for the Garbage Collector to collect the next time the GC is run. You can force garbage collection with gc_collect_cycles.

like image 42
Gordon Avatar answered Oct 15 '22 21:10

Gordon


if you use a recursive function to replace the loop the left over variables should be cleared.

just put the loop in another function any it should be in a different scope, just pass the data in and out of it.

like image 33
Joseph Le Brech Avatar answered Oct 15 '22 19:10

Joseph Le Brech