简体   繁体   English

将所有变量转换为全局范围

[英]Converting all vars to global scope

I know I can use $GLOBALS['var'] inside a function to refer to variables in the global scope. 我知道我可以在函数内使用$ GLOBALS ['var']来引用全局范围内的变量。 Is there anyway I can use some kind of a declaration inside the function so I will be able to use $var without having to use $GLOBAL['var'] every time? 无论如何,我可以在函数内使用某种声明,这样就可以使用$ var而不用每次都使用$ GLOBAL ['var']了吗?

Joel 乔尔

Although it's not recommended, but if you do want to, here's what you can do: 尽管不建议这样做,但是如果您愿意,可以执行以下操作:

If you only want to GET the values from the vars (and not SET the values), just use extract : 如果您只想从var中获取值 (而不是SET值),则只需使用extract

extract($GLOBALS);

This will extract and create all the variables in the current scope. 这将提取并创建当前范围内的所有变量。

How about using static class? 如何使用静态类?
such as

class example
{
  public static $global;
  public static function set($arr)
  {
    foreach ($arr as $key=>$val)
    {
      self::$global[$key] = $val;
    }
  }
}

function example_function()
{
   var_dump( example::$global );
}

example::set( array('a'=>1, 'b'=>2) );
example_function();

You can use the global keyword, So you can use type $var instead of $GLOBALS['var'] inside a function. 您可以使用global关键字,因此可以在函数内部使用$var类型代替$GLOBALS['var']

function myFunc() {
  global $var;
  $var = 3;
}
$var = 1;
myFunc();
echo $var;

Output: 3 输出3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM