2013-03-01 64 views
2

我有一個簡單的php函數。然而,無論如何,它每次都會失敗。php - 如果每次都失敗

function for determining tomato pic 

echo "$info[2]"; 
function tomato() 
{ 
    if(intval($info[2]) > 60) 
     return "fresh"; 
    else if(intval($info[2]) < 60) 
     return "rotten"; 
} 

它在頁面上回顯95,但然後返回「爛」。任何想法這與什麼呢?

+0

你在哪裏定義$ info?傳遞給你的函數,或(髒)使用全局:'function tomato(){global $ info; [012]「請輸入」 – 2013-03-01 23:53:57

+0

「如果確實回答了您的問題,請考慮接受答案(點擊左側的勾號) – michi 2013-04-14 12:57:00

回答

3

函數不會繼承父範圍的變量。有幾種方法解決此問題:

1:將它們作爲參數

function tomato($info) {...} 
tomato($info); 

2:如果它是一個匿名函數,使用use條款

$tomato = function() use ($info) {...} 

3:(不推薦)使用global關鍵字來導入變量

function tomato() { 
    global $info; 
    ... 
} 

4 :(非常不好的主意,但爲了完整而添加)使用$GLOBALS陣列

function tomato() { 
    // do stuff with $GLOBALS['info'][2]; 
} 
1

你必須知道的函數變量,嘗試

function tomato() { 
    global $info; 
    ... 

另外,通過該值作爲參數傳遞給函數:

function tomato($tomatocondition) { 
    if(intval($tomatocondition) > 60) 
     return "fresh"; 
    else if(intval($tomatocondition) < 60) 
     return "rotten"; 

,並調用它...

echo tomato($info[2]); 
+1

請勿使用'global'作爲參數傳遞值。 – 2013-03-01 23:47:52

+0

@crypticツ爲什麼呢? – michi 2013-03-01 23:49:20

+0

聲明全局崩潰的頁面...作爲函數雖然傳遞,謝謝! – Ted 2013-03-01 23:49:45