Heim  >  Artikel  >  Backend-Entwicklung  >  php 怎么获取一个函数内所有已定义的变量 ??

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

WBOY
WBOYOriginal
2016-10-10 11:55:571786Durchsuche

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

<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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn