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'] ever开发者_StackOverflow社区y time?
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
:
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.
function myFunc() {
global $var;
$var = 3;
}
$var = 1;
myFunc();
echo $var;
Output: 3
精彩评论