首页  >  文章  >  后端开发  >  php 怎么获取一个函数内所有已定义的变量 ??

php 怎么获取一个函数内所有已定义的变量 ??

WBOY
WBOY原创
2016-10-10 11:55:571786浏览

// 怎么做到 将其中一个作用域中的所有已定义的变量导入到另一个作用域中。

<code>function test(){
  $name = 'programmer';
  $sex  = 'male';
  $hobby = 'play computer game';
}

function test1(){
  $var_list = get_var_list('test'); // 这个函数该怎样定义才能够获取 test 函数中所有已定义的变量?
  extract($var_list);               // 将其导入到当前函数作用域中。
  echo $name;
}

test1();</code>

回复内容:

// 怎么做到 将其中一个作用域中的所有已定义的变量导入到另一个作用域中。

<code>function test(){
  $name = 'programmer';
  $sex  = 'male';
  $hobby = 'play computer game';
}

function test1(){
  $var_list = get_var_list('test'); // 这个函数该怎样定义才能够获取 test 函数中所有已定义的变量?
  extract($var_list);               // 将其导入到当前函数作用域中。
  echo $name;
}

test1();</code>

php >= 5.3.0
Put test1() into test(). Anonymous Function

<code><?php function test(){
    $name = 'programmer';
    $sex = 'male';
    $hobby = 'play computer game';
    
    //combine all variables into an associative array.
    $vars_keys = ['name', 'sex', 'hobby'];
    $vars = compact($vars_keys);
    
    //inject the variables array into test1().
    $test1 = function () use ($vars) {
        //extract the array to numerous variables.
        extract($vars);

        echo $name;
    };
    
    //you have to call it here.
    $test1();
}

test();
</code></code>

<code>function test(){
    // 把数据装入一个数组
    $res = array(
        $name = 'programmer';
        $sex  = 'male';
        $hobby = 'play computer game';
    );
    // 返回数据
    return $res;
}

function test1() {
    // 调用 text方法 拿到数据, 用 $data 来接收
    $data = test();
    
    // .......
}</code>
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn