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

查看:314
本文介绍了多个执行相同代码的案例的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

但是显然我希望代码返回three or four.

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支持":

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天全站免登陆