douxunchen3498 2013-07-20 15:12
浏览 73
已采纳

许多if语句的最合理的结构是什么?

I'm currently creating a simple login script in PHP, and there are many conditions that must be met for a successful login. To my knowledge, there are two ways of formatting the if statements that are required.

The first way, is using nested if statements:

if ($condition1 == true) {
    if ($condition2 == true) {
        if ($condition3 == true) {
            //Successful login
        } else {

        }
    } else {

    }
}

And the second way is using procedural if statements:

if ($condition1 != true) {
    die("error");
}
if ($condition2 != true) {
    die("error");
}
if ($condition3 != true) {
    die("error");
}

//successful login

Which of the two methods of dealing with many conditions is considered more logical? Are there any other methods that I haven't listed here which are better, and more logical?

  • 写回答

3条回答 默认 最新

  • duanlinpi0265 2013-07-20 15:22
    关注

    In this case it doesn't really matter, unless you want to show the user all the errors you've encountered.

    For example, you can do this:

    if($condition1 != true) {
        if($condition2 != true) {
            if($condition3 != true) {
                // Success! Login now...
            } else {
                die(error3);
            }
        } else {
            die(error2);
        }
    } else {
        die(error1);
    }
    

    In this case user will be forced to fix errors as they appear. This might take more time but is easier to understand.

    if ($condition1 != true) {
        $error = 'Error 1';
    }
    if ($condition2 != true) {
        $error .= 'Error 2';
    }
    if ($condition3 != true) {
        $error .= 'Error 3';
    }
    
    if($error != '') {
        die($error);
    } else {
        // Success! Login now...
    }
    

    In this case, user will see all errors at the same time and he or she will be able to fix all errors before submitting the form again, but more information is always harder to understand.

    Update:

    John said the right thing.

    Somewhere below, near the login form and inputs you can make a php code like this:

    <?php if($error != '') { ?><p style="color:red;"><?php echo $error; ?></p><?php } ?>
    

    Obviously, you need to use the a code like the one I've shown above to prevent the server to attempt login if an error is found.

    Hope this helps...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!