Can I pull all php global variables into the funct

2019-06-11 04:19发布

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.

2条回答
男人必须洒脱
2楼-- · 2019-06-11 04:37

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.

查看更多
别忘想泡老子
3楼-- · 2019-06-11 04:53

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.

查看更多
登录 后发表回答