【问题标题】:how to Extract variables without using extract()?如何在不使用 extract() 的情况下提取变量?
【发布时间】:2012-08-15 03:32:06
【问题描述】:

我想要一个函数将变量导出到它被调用的范围内,而不使用 extract(),例如

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

然后而不是使用:

exctract(get_vars());

我会用

get_vars();

还有吗??

【问题讨论】:

  • 您能否为您的问题添加更多细节?
  • 提取是吗?奇怪和令人不安的 :) 我猜你想将它们提取到全局变量中。也许查看此链接:stackoverflow.com/questions/2217377/…

标签: php


【解决方案1】:

你可以尝试使用global关键字

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

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

【讨论】:

    【解决方案2】:

    在 extract 函数的 php 手册中看到了可能的解决方案。 (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)
    }
    

    【讨论】:

    • 我认为上面的例子与我最初想要的不同,还是谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多