set variables to global scope within a loop

泪湿孤枕 提交于 2019-12-24 11:39:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!