2010-06-23 42 views
1

如何回顯函數中的變量?這是一個示例代碼。如何從函數回顯變量

 
function test() { 
    $foo = 'foo'; //the variable 
} 

test(); //executing the function 

echo $foo; // no results in printing it out 

+1

你只是試圖打印變量?爲什麼不在函數內部打印?你想回報嗎?或者你只是試圖打印後返回? – MJB 2010-06-23 12:51:16

+0

您無法打印未在函數之前聲明的變量。 – user29964 2010-06-23 12:52:30

回答

11

的直接回答你的問題。將導入$foo到函數的範圍:

function test() { 

    global $foo; 
    $foo = 'foo'; //the variable 
} 

更多的變量範圍在PHP here

然而,這在大多數情況下是不好的做法。您通常會想要返回函數所需的值,並在調用函數時將其分配給$foo

function test() 
    { 
     return "foo"; 
    } 

    $foo = test(); 

    echo $foo; // outputs "foo" 
3

變量的生命範圍就在函數內部。你需要聲明它是全局的,以便能夠在函數之外訪問它。

你可以這樣做:

function test() { 
    $foo = 'foo'; //the variable 
    echo $foo; 
} 

test(); //executing the function 

或者宣佈其全球的建議。要做到這一點的話,看看這裏的手冊: http://php.net/manual/en/language.variables.scope.php

2
function test() { 
    return 'foo'; //the variable 
} 

$foo = test(); //executing the function 

echo $foo; 
2

$foo變量不是函數外部可見的,因爲它只存在於功能的範圍。你可以做你想做的幾種方法:

回波函數本身:

function test() { 
    $foo = 'foo'; 
    echo $foo; 
} 

回聲返回結果:

function test() { 
    $foo = 'foo'; //the variable 
    return $foo; 
} 

echo test(); //executing the function 

使變量全球

$foo = ''; 

function test() { 
    Global $foo; 
    $foo = 'foo'; //the variable 
} 

test(); //executing the function 

echo $foo; 
0

個人我會做。

function test(&$foo) 
{ 
    $foo = 'bar'; 
} 

test($foobar); 

echo $foobar; 

使用符號中的功能參數部分告訴函數「全球化」的輸入變量,以便該變量的任何變化將直接改變功能範圍之外的一個!

+0

只要在調用test()之前定義了$ foobar以實現可讀性...儘管PHP會立即創建$ foobar – 2010-06-23 12:58:25

+0

$ foobar應該由PHP在其範圍之外創建!沒有用戶應用程序創建它,所以我的示例應該可以在外部範圍內創建$ foobar來正常工作! - http://www.php.net/manual/en/language.references.pass.php – RobertPitt 2010-06-23 13:02:06