如何在不使用 extract() 的情况下提取变量


how to Extract variables without using extract()?

我希望一个函数在不使用 extract() 的情况下将变量导出到它调用的范围,例如

function get_vars(){
  $return['a'] = 1;
  $return['b'] = 2
  return $return;
}

然后而不是使用 :

exctract(get_vars());

我只会使用

get_vars();

有没有可用的??

在提取函数的 php manuel 看到了可能的解决方案。(http://www.php.net/manual/en/function.extract.php#62727)

function free_args (&$V) {
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
    unset ($k);  unset ($v);  unset ($V);
    // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
}

您可以尝试使用global关键字

function get_vars() {
  global $a, $b;
  $a = 1;
  $b =2;
}

但对我来说,这是一种非常奇怪的方法。我更喜欢使用 OOP。