具有多个执行相同代码的 case 的 switch 语句

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

但显然我希望代码为 return three or four.

那么 return 多个 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: ...
}

您不能在一个案例中使用多个值。但是,您可以使用 "fallthrough support":

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]

如果添加的值越来越多,Switch 语句会变得越来越难维护。