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条)

报告相同问题?