2016-07-31 48 views
-1

看看我的代碼,如果我使用echo $ html_of_questions,它的工作原理。如果我使用退貨,它不起作用。爲什麼?我應該只使用回聲?因爲我被告知應該總是在函數中使用return。爲什麼返回沒有在我的功能代碼內工作,但回聲作品,PHP?

<?php 

function fruit($fruit){ 
$questions = [ 
     'q1' => '<div>Is it good?</div> 

       <input type="text" value="submit"/>', 
     'q2' => '<div>where is it from?</div> 

       <input type="text" value="submit"/>', 
     ]; 

$fruit_questions = [ 
     'apple' => [1,3,5], 
     'banana' => [1,2,4], 
     'guava' => [17,21,4], 
     ]; 

$question_keys = $fruit_questions[$fruit]; 

$html_of_questions = ''; // This will hold the questions to echo 
foreach($question_keys as $question_key){ 
    $html_of_questions .= $questions['q'.$question_key] 
} 

    return $html_of_questions;//doesn't work, use echo it works 
} 

    fruit('apple'); 
?> 
+0

你必須對結果做些什麼,'$ html = fruit('apple'); echo $ html;'這就是說,我會提醒不要從這樣的類中返回html。最佳做法是返回數據並將其分配給html。這樣它更便於攜帶,而MVC就好。責任授權,如果您希望稍後重新設置html,則可能會更難找到隱藏在某個類或某個功能中的功能。 – ArtisticPhoenix

回答

5

它的工作原理,你只是不結果做任何事情:

fruit('apple'); 

如果你想呼應的結果,你必須呼應它:

echo fruit('apple'); 

或者將它存儲在一個變量中,然後用它做點什麼:

$result = fruit('apple'); 
// other code 
echo $result; 

只調用一個函數並不會告訴系統對該函數的結果做任何事情。該函數簡單地封裝一個操作並返回一個結果。然後你必須對結果做些什麼。

+0

非常感謝。我知道了。 – conan

相關問題