具有执行相同代码的多个案例的 switch 语句 [英] switch statement with multiple cases which execute the same code

查看:30
本文介绍了具有执行相同代码的多个案例的 switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<?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';
 }

这篇关于具有执行相同代码的多个案例的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆