PHP-嵌套IF语句 [英] PHP - Nested IF statements
问题描述
我想知道何时使用多个嵌套的IF语句是个坏主意.
例如:
function change_password($email, $password, $new_password, $confirm_new_password)
{
if($email && $password && $new_password && $confirm_new_password)
{
if($new_password == $confirm_new_password)
{
if(login($email, $password))
{
if(set_password($email, $new_password))
{
return TRUE;
}
}
}
}
}
此功能的用法如下:
if(!change_password($email, $password, $new_password, $confirm_new_password)
{
echo 'The form was not filled in correctly!';
exit;
}
我这样调用我的所有函数,我想知道我的编码样式是否有问题.我对此感到疑惑,因为如果我遵循这种设计,那意味着我编写的每个函数只会与IF嵌套在一起,检查每个阶段是否存在错误.这是别人做的吗?
I call all my functions like this, and I'm wondering if there's something wrong with my coding style. I'm having my doubts because if I follow this design then that means every single function I write will just be with nested with IF's, checking if there are errors at every stage. Is this what other people do?
我看不到其他许多这样写的脚本,其中嵌套的IF呈三角形,并且仅在中间位置具有所需的结果.如果没有达到中间位置,则可能发生了问题.
I don't see many other scripts written like this, with the nested IF's making a triangle shape and only having the desired result in the very middle. If the middle isn't reached, then something screwed up.
这是一个好的功能结构吗?
推荐答案
嵌套太深通常是个坏主意-这是意大利面条式逻辑,很难遵循.由于您的每个验证步骤都取决于之前的成功步骤,因此根本不要嵌套-只需在某个步骤失败后就可以纾困:
Nesting too deeply is generally a bad idea - it's spaghetti logic and difficult to follow. Since each of your verification steps depends on the previous stage having succeeded, don't nest at all - just bail out when a stage fails:
function change_password(blah blah blah) {
if (!$condition1) {
return false;
}
if (!$condition2) {
return false;
}
etc....
// got here, must have succeeded
return true;
}
这使得可以清楚地弄清楚逻辑顺序是什么.
That makes it explicitly clear what the logic sequence is.
这篇关于PHP-嵌套IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!