Jump to content

question about variable scope and unset in a foreach loop


darth_tater

Recommended Posts

This is more of a technical question that i could not find the answer to pn the php.net manual pages.

 

take the folowing example code:

 


foreach ($array as $key => $value){

$tempvariable = some_property_of($value);

}

unset($tempvariable);

 

is that unset statement needed?  Does PHP automatically destroy the variables once the foreach loop is left?

 

 

PHP has a garbage collector that will look at stuff once it's left scope. However there are only three scopes in PHP: "global" scope, class scope, and function scope. Constructs like foreach don't have scope - when execution leaves it, any variables declared inside are still accessible (and in scope) and thus won't be destroyed.

 

In general, you don't need to worry about unset()ing variables. In general, PHP scripts run in a matter of milliseconds, and once they end PHP will clean up everything automatically.

Ok, thanks!  Thats exactly the answer i was looking for.

 

 

And i'll be using unset for:

 

1) security - you cant read or access or write a variable that no longer exists.

2) conservation - Lets not waste ram if we don't have to.

 

 

i am actively developing a web app that could end up using 20+ classes for the most complex pages....  Any optimization i can do as i am writing these functions / classes i'll need later down the road!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.