2011-05-04 71 views
0

我只是想確認以下將不起作用:函數調用,變量的作用域

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中做什麼?從手冊來看,我的選擇似乎是全球性的或根本沒有。

我只是想知道這是否正確。

+0

我知道我可以通過$測試到f2。這僅僅是爲了好奇而已。 – 2011-05-04 16:03:46

+0

好的,我只是添加了代碼,因爲我不確定,如果有其他人有同樣的問題並且看到此頁面,那就更好了。 – 2011-05-04 16:05:02

+0

試試看...這應該告訴你真的很快(比問這個問題要快得多) – ircmaxell 2011-05-04 16:37:07

回答

4

不會工作。

您可以傳遞變量,就像一個參數:

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

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

是的,我只是發表評論,因爲我想每個人都會這麼說;)謝謝你的確認。 – 2011-05-04 16:05:06

0

在F1

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

global指令使得頂級全球範圍內的本地功能部件添加global $test;。它不會重複備份功能調用棧找到名字的變量,它只是跳右後衛的絕對頂級,因此,如果你做:

$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