【发布时间】:2012-06-27 01:59:58
【问题描述】:
我对php中的switch不是很熟悉,但是我听说如果你的代码有很多elseif,最好用switch来代替。我尝试将下面的代码更改为 switch,但由于我在每个 elseif 处检查两个或三个值,因此似乎使用 elseif 而不是 switch 对我来说更合乎逻辑(也许我错了)。
所以我的问题是,您对下面的代码有何建议? Elseif 还是 switch?
如果我想把代码改成switch,你能给我一些提示吗?
非常感谢您!
(顺便说一句,block_check 和 report_check 是复选框,reported_msg 是文本)
public function block_user(){
if(isset($_POST['submitted'])){
$block_check = $_POST['block_check'];
$report_check = $_POST['report_check'];
$reported_msg = $_POST['reported_msg']);
if((!($block_check)) && (!($report_check))){
echo "dont send, both not checked";
}elseif(($report_check) && ($reported_msg == '')){
echo "dont send, msg box is empty";
}elseif((!($report_check)) && ($reported_msg != '')){
echo "dont send, report_check is not checked";
}elseif(($block_check) && (!($report_check)) && ($reported_msg == '')){
echo "just process block";
}elseif((!($block_check)) && ($report_check) && ($reported_msg != '')){
echo "just process report";
}elseif(($block_check) && ($report_check) && ($reported_msg != '')){
echo "process both block and report";
}
}
}
【问题讨论】:
-
如果你要检查多个这样的值,你可能会被 elseifs 卡住。它们没有任何问题,只是打字多一些,阅读难度稍大一些。
-
@Andrew 感谢您的评论。我只会使用 elseif。
-
你使用了很多不需要的括号。如果它像那样大,解释器运行您的代码需要更长的时间。例如,您的第一个 if 语句 (
if((!($block_check)) && (!($report_check))){) 可以重写为:if(!$block_check && !$report_check){。 -
@C0deH4cker 感谢您的评论!学到了一些我不知道的东西。我一定会解决的!
标签: php switch-statement if-statement