2012-07-31 45 views
1

我有一個config.php文件,它有一些常量和方法。
我有一個test.php文件,它調用config.php中的一種方法。
相關的代碼是:PHP的數組不會評價

$Questions = array(
    1 => "Is he/she nice?1", 
    2 => "Is he/she sweet?2", 
    3 => "Is he/she nice?3", 
    4 => "Is he/she sweet?4", 
    5 => "Is he/she nice?5", 
    6 => "Is he/she sweet?6", 
    7 => "Is he/she nice?7", 
    8 => "Is he/she sweet?8", 
    9 => "Is he/she nice?9", 
    10 => "Is he/she sweet?10" 
); 


function PrintAnswersOnMe($uid) 
{ 
    $uid = antiSQLi($uid); 
    $query = "SELECT * FROM AnsAns WHERE fid='".$uid."'"; 
    $result = mysql_query($query); 
    while($row = mysql_fetch_array($result)) 
    { 
     $rrr = $row[2]; 
     echo $Questions[1]; 
     echo $rrr . ' ' . $Questions[$rrr]; 
     echo "You'r friend <img src='http://graph.facebook.com/".$row['uid']."/picture/' /> answered " . (($row['answer'] == 1) ? "yes" : "no") . " about wether you're ". $rrr.": " . $Questions[$rrr]; 
     echo "<br /> " . $Questions['2'] . "<br/>"; 
    } 
} 


test文件只要求PrintAnswersOnMe。 (它包含它)
一切工作文件,excpet那沒有$Question[...]評估到實際的HTML輸出!
要檢查,我已經添加了$Questions[2] - 還有$Questions['2'] - 並且它們都沒有生成HTML輸出。循環會執行,因爲其他所有內容都會轉到HTML。
有趣的是,它內部的test.php它的工作原理 - echo $Questions[...]實際上是產品到HTML輸出。有人對這種神祕的行爲有任何想法嗎?

+0

你在哪裏定義$問題?在包含的文件中,還是在調用腳本?如果它在include中定義,我相信它不在調用PrintAnswersOnMe()的範圍內 – ernie 2012-07-31 23:32:30

+0

該變量超出函數的範圍。 http://php.net/manual/en/language.variables.scope.php進一步閱讀 – pbond 2012-07-31 23:36:50

+0

老兄,請獲取一些_basic_ PHP知識。 http://www.php.net/manual/en/language.variables.scope.php – CBroe 2012-08-01 09:04:31

回答

1

$uid = antiSQLi($uid);之前,您需要將global $Questions;添加到函數的開頭。

+2

noooooooooo :-) global bad;只是將其解析爲函數的參數 – 2012-07-31 23:33:20

+0

爲什麼全局不好?這已經是全球性的了,所以修復它以使其正常工作並沒有什麼壞處。它似乎不會在每次調用時發生變化,所以它不一定是一個參數 – dririan 2012-07-31 23:36:42

+0

我相信這是最好的解決方案。謝謝! – 2012-08-01 11:17:57

2
function PrintAnswersOnMe($uid, $questions) { 
//Code goes here 
} 

然後,你將有機會獲得

+0

這需要調用'PrintAnswersOnMe'來將其作爲參數添加。 – dririan 2012-07-31 23:38:30