Joel
Joel

Reputation: 6107

Converting all vars to global scope

I know I can use $GLOBALS['var'] inside a function to refer to variables in the global scope. 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?

Joel

Upvotes: 1

Views: 102

Answers (3)

Bob Fanger
Bob Fanger

Reputation: 29897

You can use the global keyword, So you can use type $var instead of $GLOBALS['var'] inside a function.

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

Output: 3

Upvotes: 1

shamittomar
shamittomar

Reputation: 46692

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:

extract($GLOBALS);

This will extract and create all the variables in the current scope.

Upvotes: 1

ajreal
ajreal

Reputation: 47321

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();

Upvotes: 1

Related Questions