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

2022-01-19 00:00:00 switch-statement php case

我有以下代码:

<?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

但显然我希望代码返回三个或四个.

But obviously I want the code to return three or four.

那么,为多个 case 语句返回相同代码的正确方法是什么?

So what is right method to return the same code for multiple case statements?

推荐答案

不可能.case 项必须是 VALUES.你有表达式,这意味着表达式被评估,并且该表达式的结果是将它们与 switch() 中的值进行比较.这意味着你有效地得到了

Not possible. the case items must be VALUES. You have expressions, which means the expressions are evaluated, and the result of that expression is them compared against the value in the switch(). That means you've effectively got

switch(...) { 
  case TRUE: ...
  case TRUE: ...
}

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

You cannot use multiple values in a case. YOu can, however, use the "fallthrough support":

switch(...) {
   case 'one':
   case 'two':
       return 'one or two';
   case 'three':
   case 'four':
       return 'three or four';
 }

相关文章