is there a way to reset all the previously declared variables at some point in the php ? I want to use it to combine 2 (or more) php files into a single one, but the problem is those php files use same names of variables but for different purposes. So i want to reset all the variables after each chunk of the php is executed. E.G. file 1 for ($i=0; $i<100; $i++) { $var1 += $i*$i; } PHP: file 2 $var1 = 0; if ($_POST['submit']) { $var1 = 1; } if ($var1) { //do some action } PHP: as you can see if you combine these 2 files into a single one there will be a logical error and the "do some action" part will be executed regardless if there was a "submit" request in POST or not .. so i need to reset ALL (undefined amount of them) variables in between the merging point of these 2 files. Any suggestions ? Thanks
I didn't test it but I hope it works. If by resetting you mean to simply distroy them. $vars = array_keys(get_defined_vars()); foreach($vars as $var) { unset(${"$var"}); # or may be reset them to empty string# ${"$var"} = ""; } Code (markup): regards
This is what user required and is supplied. Beides, what else you didn't like in it? unset releases the ocupied memory by variables, and I assume that is what he wants also ${"$var"} = ""; is supplied in code you look closely, how do you want it to be ?
Hi, Using an array may be better option for you, for example; You can store the first file in: $files['file1'] The second file inside $files['file2'] You'll be able to unset any element of the array and also combine them when you like with inbuilt array functions such as array_merge. More information here What Vooler said above will work, by using unset - But it's not good practice to name all the variables the same name, makes it untiny and harder to debug if anything goes wrong. Just a suggestion. Regards, Steve
You can also just require those two files from inside two distinct functions: function methodA() { require 'a.php';` //return whatever result variable it may be } function methodB() { require 'b.php'; //return whatever result variable it may be } $a = methodA(); $b = methodB(); PHP:
Vooler Thanks, seems this is just what i needed. The get_defined_vars() is the key to the solution for me. I know this is shitty programming practice, but the thing is that i already have the code written and now it needs to be combined (lots of code). And i happen to be lazy enough that don't want to go over variables and figure out what to rename them to Thanks again
Yes ofcourse, it is not recommended method, this is what you wanted, "the shitty method", beides use: $vars["user"] // user index