doushan5222 2012-08-07 04:28
浏览 27
已采纳

PHP - 嵌套的IF语句[关闭]

I'm wondering when it's a bad idea to use multiple nested IF statements.

eg:

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;
                }
            }
        }
    }
}       

This function is used like this:

if(!change_password($email, $password, $new_password, $confirm_new_password)
{
    echo 'The form was not filled in correctly!';
    exit;
}

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?

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.

Is this a good function structure?

  • 写回答

3条回答 默认 最新

  • doune1000 2012-08-07 04:31
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度