>  기사  >  백엔드 개발  >  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
test1()을 test()에 넣으세요

<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으로 문의하세요.