switch statement without break

后端 未结 6 1550
粉色の甜心
粉色の甜心 2021-01-17 21:35

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) {
          


        
6条回答
  •  攒了一身酷
    2021-01-17 22:31

    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 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 \Base\User)) {
                throw new \Exception(get_class($value)." given. \Base\User 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.

提交回复
热议问题