darth_tater Posted January 8, 2011 Share Posted January 8, 2011 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? Link to comment https://forums.phpfreaks.com/topic/223756-question-about-variable-scope-and-unset-in-a-foreach-loop/ Share on other sites More sharing options...
requinix Posted January 8, 2011 Share Posted January 8, 2011 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. Link to comment https://forums.phpfreaks.com/topic/223756-question-about-variable-scope-and-unset-in-a-foreach-loop/#findComment-1156595 Share on other sites More sharing options...
darth_tater Posted January 8, 2011 Author Share Posted January 8, 2011 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! Link to comment https://forums.phpfreaks.com/topic/223756-question-about-variable-scope-and-unset-in-a-foreach-loop/#findComment-1156596 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.