我有以下代码,并想知道是否有更好的方法来使用if-else和相同的结果,而不是使用相同的其他三次?
if($condition1) {
// some code to get condition 2
if($condition2) {
// some code to get condition 3
if($condition3) {
$dt = $something;
} else {
$dt = "";
}
} else {
$dt = "";
}
} else {
$dt = "";
}
答案 0 :(得分:1)
您可以轻松删除一些额外的else
语句。
$dt = ""; // Assign $dt in the beginning
if ($condition1) {
// some code to get condition 2
if ($condition2 && $condition3) {
// some code to get condition 3
$dt = $something;
}
}
答案 1 :(得分:0)
避免嵌套语句的两种方法。
使用函数
$dt = doSomething($params);
function someFunction ($params) {
if (!$condition1) {
return "";
}
// do stuff for condition 1
if (!$condition2) {
return "";
}
// do stuff for condition 2
if (!$condition3) {
return "";
}
return $something;
}
使用do / while语句
do {
$dt = "";
if (!$condition1) {
break;
}
// do stuff for condition 1
if (!$condition2) {
break;
}
// do stuff for condition 2
if (!$condition3) {
break;
}
$dt = $something;
} while (0); // since this will evaluate to false it will not loop at all.