PHP - 仅在成功切换时运行代码

时间:2012-12-06 23:31:19

标签: php switch-statement

寻找更简单的方法:

$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
}

可能仅针对defaultany的其他案例关键字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) //... 

试过这个无济于事,但只想说明我的意图。

7 个答案:

答案 0 :(得分:4)

在顶部尝试$switch_success=1;,在切换结束时尝试default: $switch_success=0;

答案 1 :(得分: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
}

答案 2 :(得分:1)

case子句默认为直通。

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

但是如果你有针对每个案例做的事情,然后为所有事情要做的事情,你的原始例子就可以了。

答案 3 :(得分:1)

如果我理解正确,如果符合任何的情况,您希望$ success成功,否则为false?如果是这样,设置$ success = true;在开始时,你的“默认”案例是$ success = false;然后你不必输入$ success = true;很多次。

答案 4 :(得分: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
}

答案 5 :(得分:0)

我想不出更短的版本

if ($var == 'a' || $var == 'b' || $var == 'c') // do some stuff;

答案 6 :(得分: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
}