Switch/Case 没有 `break`,不能正确检查案例 [英] Switch/Case without a `break`, doesn't check the cases properly

查看:51
本文介绍了Switch/Case 没有 `break`,不能正确检查案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了 switch case 条件的问题.

I'm having trouble with a switch case conidtion.

为什么在以下场景中:

$category = "A";
$offer = "none";
$discount = "none";

对于以下代码:

switch (TRUE) {

case ($category == 'A') : / #1

    $msg = "hello"; 

case ($offer == 'special') : / #2

        $id = "123"; 

case ($discount == '50D') : / #3

        $id = "999";


break;

echo $id;

}

即使 #2#3 未满,我也得到 999 的输出 id?

I get output of 999 for id, even though #2 and #3 are not fullfilled?

诸如$offer == 'special' 的情况是一般情况的私有情况,即$category == 'A'.这就是为什么我希望函数按此顺序运行.如果 switch/case 不合适,我应该用什么?

Cases such as $offer == 'special' are private cases of the general case which is $category == 'A'. That's why I want the function to go in this order. if switch/case is not appropriate, what shall I use?

推荐答案

一旦 switch 找到匹配的 case,它就会执行所有剩余的代码,直到遇到一个break 语句.以下 case 表达式均未经过测试,因此您不能拥有这样的依赖项.要实现子案例,您应该使用嵌套的 switchif 语句.

Once switch finds a matching case, it just executes all the remaining code until it gets to a break statement. None of the following case expressions are tested, so you can't have dependencies like this. To implement sub-cases, you should use nested switch or if statements.

switch ($category) {
case 'A':
    $msg = 'hello';
    if ($offer == 'special') {
        $id = '123';
    } elseif ($discount == '50D') {
        $id = '999';
    }
    break;
...
}
echo $id;

case 没有 break 的 fallthrough 特性最常用于当你有两个 case 应该做完全相同的事情时.所以第一个有一个没有中断的空代码,它只是失败了.

The fallthrough feature of case without break is most often used when you have two cases that should do exactly the same thing. So the first one has an empty code with no break, and it just falls through.

switch ($val) {
case 'AAA':
case 'bbb':
    // some code
    break;
...
}

当两种情况相似,但其中一种需要先运行一些额外的代码时,也可以使用它:

It can also be used when two cases are similar, but one of them needs some extra code run first:

switch ($val) {
case 'xxx':
    echo 'xxx is obsolete, please switch to yyy';
case 'yyy':
    // more code
    break;
...
}

这篇关于Switch/Case 没有 `break`,不能正确检查案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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