Reputation: 37834
In order to use variables outside of a function, I have to do this:
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
What if there are a lot of global variables, and I just want them all to be locally scoped inside the function? How do I do this without maintaining a long list of global declarations at the beginning of each function? I'm not concerned about best practices, or all the reasons it may be considered dangerous.
Upvotes: 0
Views: 460
Reputation: 14302
Ideally, everything your function needs should be in a parameter.
function Sum($a, $b) {
return $a + $b;
}
If you really can't avoid referring to variables outside your function scope, you have several options:
Use the $GLOBALS array:
function Sum() {
return $GLOBALS['a'] + $GLOBALS['b'];
}
Use the global
keyword:
function Sum()
global $a, $b;
return $a + $b;
}
Use an "anonymous" function and inject the globals
$Sum = function() use ($a, $b) {
return $a + $b;
}
$result = $Sum();
Anonymous functions are more useful if you want to work with variables in-scope of the functional declaration that aren't global.
extract() them from $GLOBALS
function Sum() {
extract($GLOBALS);
return $a + $b;
}
This last option will pull in all globals, and seems to be what you're looking for.
But seriously, parametize whenever possible.
Upvotes: 1
Reputation: 212412
Why aren't you doing something like:
$a = 1;
$b = 2;
function Sum()
{
$args = func_get_args();
$result = 0;
foreach($args as $arg) {
$result += $arg;
}
return $result;
}
$b = Sum($a, $b);
echo $b;
which is then more generic, capable of accepting different arguments, or more than two arguments, and useful in a lot more situations.
Upvotes: 2