问题
I want to define a number of temporary global variables in PHP called $MyGlobalVar1
, $MyGlobalVar2
... , but the problem is that the keyword 'global' takes the variable name literally:
for ($i = 1; $i<= 10; $i++) {
$var = '$MyGlobalVar'.$i;
global $var;
}
i.e. $var
is now global.
Setting quotes will not work because 'global' expects '$' and will stop execution at the single quote:
for ($i = 1; $i<= 10; $i++) {
$var = '$MyGlobalVar'.$i;
global '$var';
}
How to set the variables to global scope? Thanks.
回答1:
since you using '
it will always be taken as string
Try $GLOBALS for your purpose
for ($i = 1; $i<= 10; $i++)
{
// acess as $GlOBALS['MyGlobalVar'.$i] and do whatever you want
$GLOBALS['MyGlobalVar'.$i] = null
}
回答2:
You should be able to do the following as well:
for ($i = 1; $i<= 10; $i++) {
$varName = 'MyGlobalVar'.$i;
global $$varName;
}
回答3:
This is because single quotes can't parse variables you have to use double quotes. You should know the basic difference between them.
First of all you do not need quotes around the global variable try this
global $var;
回答4:
You can possibly try variabling your variable ie:
for ($i = 1; $i<= 10; $i++) {
$var = '$MyGlobalVar'.$i;
$foo = $var;
global $foo;
}
来源:https://stackoverflow.com/questions/16515069/set-variables-to-global-scope-within-a-loop