<分区>
我想到有许多不同的方法来构造条件逻辑。据我所知,只要我们设置错误以结束脚本(或者您可以想象相同的示例但在函数中返回),那么以下示例是相同的:
示例 1
if($condition1) {
trigger_error("The script is now terminated");
}
if($condition2) {
trigger_error("The script is now terminated");
}
echo "If either condition was true, we won't see this printed";
示例 2
if(!$condition1) {
if(!$condition2) {
echo "If either condition was true, we won't see this printed";
}
else {
trigger_error("The script is now terminated");
}
}
else {
trigger_error("The script is now terminated");
}
示例 3
if($condition1) {
trigger_error("The script is now terminated");
}
else {
if($condition2) {
trigger_error("The script is now terminated");
}
else {
echo "If either condition was true, we won't see this printed";
}
}
示例 4 -- 改编自 Fraser's Answer
function test($condition) {
if($condition) {
trigger_error("The script is now terminated");
}
}
test($condition1);
test($condition2);
echo "If either condition was true, we won't see this printed";
就个人而言,我倾向于编写示例 1 中的代码。这是因为我觉得通过以这种方式检查结束脚本(或函数)的条件,我可以清楚地定义脚本执行和未执行的内容,即所有内容在条件执行之前,该行之后的所有内容都没有执行。这意味着当我在第 147 行遇到错误时,我会立即知道发生了什么,这有助于我更快地找到错误。此外,如果我突然意识到我需要在 $condition1 之前测试 $condition2,我可以通过简单的复制粘贴进行更改。
我看到很多代码都像示例 2 中那样编写,但对我来说,调试起来似乎要复杂得多。这是因为,当嵌套太大时,错误将在底部的某个较远的行触发,并与由大量嵌套代码引起的错误条件分开。此外,更改条件序列可能会更加困惑。
您可以混合使用这两种样式,例如示例 3,但这似乎会使事情过于复杂,因为所有“else”本质上都是多余的。
我错过了什么吗?构建条件代码的最佳方式是什么?有比这些例子更好的方法吗? 是否存在一种风格可能优于另一种风格的特定情况?
编辑:示例 4 看起来很有趣,我没有考虑过。您还可以将错误消息作为第二个参数传递。
谢谢!
附言请记住,我可能需要在检查 $condition1 和 $condition2 之间执行一些任意步骤,因此任何替代方案都必须适应这一点。否则,还有更好的选择,例如 if($condition1 || $condition2)。