note 91982 added to language.variables.scope
| From: | emartin at sigb dot net | Date: | Fri, 03 Jul 2009 14:32:45 +0000 |
| Subject: | note 91982 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-157882@lists.php.net to get a copy of this message | ||
If you are used to include files which declare global variables, and if you now need to include
these files in a function, you will see that those globals are declared in the function's scope
and so they will be lost at the end of the function.
You may use something like this to solve this problem:
main_file.php :
<?php
//Some innocent variables which exist before the problem
$a = 42;
$b = 33;
$c = 56;
function some_function() {
//Some variables that we don't want out of the function
$saucisse = "saucisse";
$jambon = "jambon";
//Let's include another file
$evalt = "require_once 'anothertest_include.php';";
$before_eval_vars = get_defined_vars();
eval($evalt);
//Let's extract the variables that were defined AFTER the call to 'eval'
$function_variable_names = array("function_variable_names" => 0,
"before_eval_vars" => 0, "created" => 0);
//We can generate a list of the newly created variables by substracting the list of the variables
of the function and the list of the variables which existed before the call to the list of current
variables at this point
$created = array_diff_key(get_defined_vars(), $GLOBALS, $function_variable_names,
$before_eval_vars);
//Now we globalize them
foreach ($created as $created_name => $on_sen_fiche)
global $$created_name;
//And we affect them
extract($created);
}
some_function();
print_r(get_defined_vars());
?>
included_file.php :
<?php
//Some variables that we want in the global scope of main_file.php
$included_var_one = 123;
$included_var_two = 465;
$included_var_three = 789;
?>
----
Server IP: 69.147.83.197
Probable Submitter: 82.127.45.130
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/91982
Del: integrated -- https://master.php.net/note/delete/91982/integrated
Del: useless -- https://master.php.net/note/delete/91982/useless
Del: bad code -- https://master.php.net/note/delete/91982/bad+code
Del: spam -- https://master.php.net/note/delete/91982/spam
Del: non-english -- https://master.php.net/note/delete/91982/non-english
Del: in docs -- https://master.php.net/note/delete/91982/in+docs
Del: other reasons-- https://master.php.net/note/delete/91982
Reject -- https://master.php.net/note/reject/91982
Search -- https://master.php.net/manage/user-notes.php