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.
Ideally, everything your function needs should be in a parameter.
If you really can't avoid referring to variables outside your function scope, you have several options:
Use the $GLOBALS array:
Use the
global
keyword:Use an "anonymous" function and inject the globals
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
This last option will pull in all globals, and seems to be what you're looking for.
But seriously, parametize whenever possible.
Why aren't you doing something like:
which is then more generic, capable of accepting different arguments, or more than two arguments, and useful in a lot more situations.