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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With