Home >Backend Development >PHP Tutorial >How to get all defined variables in a function in php? ?

How to get all defined variables in a function in php? ?

WBOY
WBOYOriginal
2016-10-10 11:55:571864browse

// How to do it: Import all defined variables in one scope into another scope.

<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>

Reply content:

// How to do it: Import all defined variables in one scope into another scope.

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

function test1() {
    // 调用 text方法 拿到数据, 用 $data 来接收
    $data = test();
    
    // .......
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn