函数内部函数调用,变量范围

时间:2011-05-04 16:01:32

标签: php scope

我只想确认以下内容不起作用:

function f1(){
  $test = 'hello';
  f2();
}

function f2(){
  global $test;
  echo $test;
}

f1(); //expected result 'hello'

http://php.net/manual/en/language.variables.scope.php

有没有办法像在Javascript中一样“流动”范围链?从手册中可以看出,我对此的选择是全局的,或者根本没有。

我只是想知道这是否正确。

3 个答案:

答案 0 :(得分:4)

不会工作。

您可以将变量作为参数传递:

function f1(){
  $test = 'hello';
  f2($test);
}

function f2($string){
  echo $string;
}
f1(); //expected result 'hello'

答案 1 :(得分:0)

在f1

中添加global $test;
function f1(){
    global $test;
    $test = 'hello';
    f2();
}

答案 2 :(得分:0)

global指令使本地函数成为顶级全局范围的一部分。它不会迭代备份函数调用堆栈来查找该名称的变量,它只是直接跳回到绝对顶层,所以如果你完成了:

$test = ''; // this is the $test that `global` would latch on to
function f1() { ... }
function f2() { ... }

基本上,请考虑global相当于:

$test =& $GLOBALS['test']; // make local $test a reference to the top-level $test var 
相关问题