1

寻找更简单的方法来完成:

$switch_success = false;
switch ($var){
    case "a":
        // do some stuff
        $switch_success = true;
        break;
    case "b":
        // do some stuff
        $switch_success = true;
        break;
    case "c":
        // do some stuff
        $switch_success = true;
        break;
}
if ($switch_success){
    // switch was successful - run once only if switch finds a matching case
}

可能是另一个 case 关键字,例如default仅 for anyor all

case "c":
    // do some stuff
    break;
all:
    // switch was successful - run once only if switch finds a matching case

或者可能 ...

$switch_success = switch ($var){
    case "a":
    // do some stuff
    break;
    case "b":
    // do some stuff
    break;
    case "c":
    // do some stuff
    break;
}
if ($switch_success) //... 

只是尝试了无济于事,但只是想说明我的意图。

4

7 回答 7

4

$switch_success=1;在顶部和default: $switch_success=0;开关末端尝试。

于 2012-12-06T23:36:27.170 回答
2

怎么样...之类的

$switch_success = true;
switch ($var)
{
    case "a":
        // do some stuff
        break;
    case "b":
        // do some stuff
        break;
    case "c":
        // do some stuff
        break;
    default:
        $switch_success = false;
}
if ($switch_success){
    // switch was successful - run once only if switch finds a matching case
}
于 2012-12-06T23:38:47.377 回答
1

默认情况下,该case子句已失效。

switch ($var){
    case "a":
    case "b":
    case "c":
        // do some stuff
        break;
    default
        // do nothing
        break;
}

但是,如果您要为每个案例做一些事情,然后再为所有事情做一些事情,那么您的原始示例就可以了。

于 2012-12-06T23:37:49.107 回答
1

如果我对您的理解正确,您希望 $success 在满足任何一种情况时为真,否则为假?如果是这样,设置 $success = true; 一开始,让你的“默认”案例为 $success = false; 然后你不必输入 $success = true; 一堆时间。

于 2012-12-06T23:38:28.420 回答
1

也许这个?

$switch_success = true;
switch ($var){
    case "a":
        // do some stuff
        break;
    case "b":
        // do some stuff
        break;
    case "c":
        // do some stuff
        break;
    default:
        $switch_success = false;
        break;
}
if ($switch_success){
    // switch was successful - run once only if switch finds a matching case
}
于 2012-12-06T23:40:21.047 回答
0

我想不出更短的版本

if ($var == 'a' || $var == 'b' || $var == 'c') // do some stuff;
于 2012-12-06T23:36:47.857 回答
0

我会$switch_success单独设置,例如:

$switch_success = in_array($var, array("a","b","c"));

switch ($var) {
    case "a":
        // do some stuff
        break;
    case "b":
        // do some stuff
        break;
    case "c":
        // do some stuff
        break;
}

if ($switch_success) {
    // switch was successful
}
于 2012-12-06T23:37:06.173 回答