开发者

Why does PHP NOT clear memory after leaving loops?

for($i=0; $i<3; $i++) {
    echo '$i = ' . $i . '<br开发者_Go百科/>' ;
}
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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜