首頁  >  文章  >  後端開發  >  php 怎麼取得一個函數內所有已定義的變數 ? ?

php 怎麼取得一個函數內所有已定義的變數 ? ?

WBOY
WBOY原創
2016-10-10 11:55:571785瀏覽

// 怎麼做到 將其中一個作用域中的所有已定義的變數匯入到另一個作用域中。

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

function test1() {
    // 调用 text方法 拿到数据, 用 $data 来接收
    $data = test();
    
    // .......
}</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn