note 91982 deleted from language.variables.scope by cmb
| From: | cmb@php.net | Date: | Sun, 27 Oct 2019 08:31:16 +0000 |
| Subject: | note 91982 deleted from language.variables.scope by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212782@lists.php.net to get a copy of this message | ||
Note Submitter: emartin at sigb dot net
----
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;
?>