使用直通开关

Que*_*low 6 php switch-statement

在研究使用switch语句的更好方法时,我发现了这个stackoverflow示例.我想做类似的事情,但有一个转折点:

switch($status)
{
 case "a":
 case "b":
  echo "start execute code for case a and b";
 case "a":
  echo "continue to execute code for case a only";
 case "b":
  echo "continue to execute code for case b only";
 case "a":
 case "b":
  echo "complete code execution for case a and b";
 break;
 case "c":
  echo "execute code for case c";
 break;
 case "d":
  echo "execute code for case d";
 break;
 case "e":
  echo "execute code for case e";
 break;
 case "f":
  echo "execute code for case f";
 break;
 default:
  echo "execute code for default case";
}
Run Code Online (Sandbox Code Playgroud)

是的,上述情况显然不能按计划进行,因为案例"a"将会一直持续下去,直到达到一个break.我只是想知道是否有一种方法可以优雅地执行此操作而无需重复太多代码.

Que*_*low 8

以下是我认为优雅的解决方案:

switch($status)
{
 case "a":
 case "b":
  echo "start execute code for case a and b";
  if($status == "a") echo "continue to execute code for case a only";
  if($status == "b") echo "continue to execute code for case b only";
  echo "complete code execution for case a and b";
 break;
 case "c":
  echo "execute code for case c";
 break;
 case "d":
  echo "execute code for case d";
 break;
 case "e":
  echo "execute code for case e";
 break;
 case "f":
  echo "execute code for case f";
 break;
 default:
  echo "execute code for default case";
}
Run Code Online (Sandbox Code Playgroud)

我不想在这里发明任何新东西.只是想从这里的每个人的经验中学习.感谢所有为我提供答案的人.


Mar*_*c B 5

一旦case匹配,PHP将忽略任何进一步的case语句并执行所有代码,直到交换机关闭(})或break遇到a.break也将终止开关,所以你想要的是不可能的.