无间断的 switch 语句

2022-01-19 00:00:00 switch-statement php

switch语句中不包含break的case选项怎么会自动转发到下一个case而不检查?

How come a case option in a switch statement that does not contain a break automatically forwards to a next case without check?

try {
    switch($param) {
        case "created":
            if(!($value instanceof DateTime))
                throw new Exception("DateTime expected, ".gettype($value)." given for self::$param");
        case "Creator":
            if(!($value instanceof BaseUser)) {
                throw new Exception(get_class($value)." given. BaseUser expected for self::$Creator");                  
            }
        default:
            $this->$param = $value;
            break;
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

如果参数是创建"的,它将在创建的情况下进行检查,这很好.当检查成功时,我希望代码继续使用默认选项,这就是为什么没有 break;.但相反,它在 $param != "Creator"! 时继续创建者"!

If the param is "created" it will do the check in the created-case, which is good. When the check is succesful, I want the code to continue to the default option, that's why there is no break;. But instead it continues to "Creator" while $param != "Creator"!

我确实知道如何解决这个问题(只需在创建"的情况下添加默认代码),但我不喜欢经常重复该代码.我的实际问题是:为什么它继续使用创造者"案例,而案例不是创造者".

I do know how to solve this (just add the default code in my case "created"), but I don't like to repeat that code too often. My actual question is: Why does it continue with the "Creator" case while the case is not "Creator".

推荐答案

Fallthrough 是一个有意的设计功能,允许以下代码:

Fallthrough was an intentional design feature for allowing code like:

switch ($command) {
  case "exit":
  case "quit":
    quit();
    break;
  case "reset":
    stop();
  case "start":
    start();
    break;
}

它的设计是为了逐个执行执行.

It's designed so that execution runs down from case to case.

default 与任何其他情况一样,只是在没有触发其他情况时会跳转到那里.这绝不是在运行实际选定的案例后执行此操作"指令.在您的示例中,您可以考虑:

default is a case like any other, except that jumping there happens if no other case was triggered. It is not by any means a "do this after running the actual selected case" instruction. In your example, you could consider:

  switch($param) {
    case "created":
        if(!($value instanceof DateTime))
            throw new Exception("DateTime expected, ".gettype($value)." given for self::$param");
        break;
    case "Creator":
        if(!($value instanceof BaseUser)) {
            throw new Exception(get_class($value)." given. BaseUser expected for self::$Creator");                  
        }
        break;
}

$this->$param = $value;

这里的经验法则是,如果它不依赖于交换机,则将其移出交换机.

The rule of thumb here is, if it doesn't depend on the switch, move it out of the switch.

相关文章