【发布时间】:2011-05-08 12:26:20
【问题描述】:
switch语句中不包含break的case选项怎么会自动转发到下一个case而不检查?
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 \Base\User)) {
throw new \Exception(get_class($value)." given. \Base\User expected for self::\$Creator");
}
default:
$this->$param = $value;
break;
}
} catch(Exception $e) {
echo $e->getMessage();
}
如果参数是“创建的”,它将在创建的情况下进行检查,这很好。当检查成功时,我希望代码继续使用默认选项,这就是为什么没有 break;。但相反,它在 $param != "Creator"! 时继续“创建者”!
我确实知道如何解决这个问题(只需在“创建”的情况下添加默认代码),但我不喜欢经常重复该代码。我的实际问题是:为什么它会继续使用“Creator”案例,而该案例不是“Creator”。
【问题讨论】:
标签: php switch-statement