I would like to merge two php projects. Both projects use global variables so I would like to have separate global scopes.
Example:
file project1.php:
$var1 = 'var1';
function print1() {
global $var1;
echo $var1;
}
print1();
file project2.php:
function load1() {
include('project1.php');
}
$var2 = 'var2';
function print2() {
global $var2;
echo $var2;
}
print2();
load1();
This would execute project2 just as expected but project1 would fail because $var1 is not in global scope but in the scope of load1().
One possible fix would be to call global $var1 in load1() but that would mix the two global scopes (messy) and would be complex since the reallive project2 has many global variables and I would have to check if there are any new ones with each update.
So it would be best if I could create a seperate global scope for project1. Is that possible?
It is not possible to have separate GLOBAL contexts. The sole purpose of the global of the global context is to be “global” whatever happens.
In order to fix this, you should “contextualize” your code refactoring global variables to function arguments :
Becomes :