开发者

Function call from within function, variable scope

I just want to confirm that the following will NOT work:

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

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

f1(); //expected result 'hello开发者_StackOverflow中文版'

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

Is there no way to just "flow" up the scope chain like you can do in Javascript? From the manual, it seems that my option for this is global or nothing at all.

I just wanted to know if that was correct.


It won't work.

You can pass the variable as a parameter though :

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

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


Add global $test; in f1

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


The global directive makes a local function part of the top-level global scope. It won't iterate back up the function call stack to find a variable of that name, it just hops right back up to the absolute top level, so if you'd done:

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

Basically, consider global to be the equivalent of:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜