[英]switch statement with multiple cases which execute the same code
我有以下代碼:
<?php
echo check('three');
function check($string) {
switch($string) {
case 'one' || 'two' : return 'one or two'; break;
case 'three' || 'four' : return 'three or four'; break;
}
}
目前它輸出:
one or two
但顯然我希望代碼返回three or four
。
那么為多個case語句返回相同代碼的正確方法是什么?
只需編寫兩個執行相同代碼的case語句,例如
function check($string) {
switch($string) {
case 'one':
case 'two':
return 'one or two';
break;
case 'three':
case 'four' :
return 'three or four';
break;
}
}
不可能。 case
項必須是VALUES 。 你有表達式,這意味着要計算表達式,並將該表達式的結果與switch()
中的值進行比較。 這意味着你已經有效了
switch(...) {
case TRUE: ...
case TRUE: ...
}
您不能在案例中使用多個值。 但是,你可以使用“秋天支持”:
switch(...) {
case 'one':
case 'two':
return 'one or two';
case 'three':
case 'four':
return 'three or four';
}
如何使用映射字典:
$oneOrTwo = 'one or two';
$threeOrFour = 'three or four';
$stringsMap = ['one' => $oneOrTwo, 'two' => $oneOrTwo, 'three' => $threeOrFour, 'four' => $threeOrFour];
return $stringsMap[$string]
如果添加越來越多的值,切換語句將變得越來越難以維護。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.