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