PHP - Nested IF statements [closed]

只谈情不闲聊 提交于 2019-11-30 09:01:36

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.

I think it is definitely well readable and can easily be understood in comparison to using just one if statement like

if (blah and blah and blah and blah and blah and blah and blah) {}

However I'd still prefer doing it this way - too much indention can get kinda annoying:

function change_password($email, $password, $new_password, $confirm_new_password)
{
    if (!$email || !$password || !$new_password || !$confirm_new_password) return false;
    if ($new_password != $confirm_new_password) return false;
    if (!login($email, $password)) return false;
    if (!set_password($email, $new_password)) return false;

    return true;
}

It can be good to nest them, because by changing the order you may be able to avoid making extra comparisons. What you are doing now looks good, however your function would be less efficient if you instead wrote it as:

function change_password($email, $password, $new_password, $confirm_new_password)
{
    if($new_password == $confirm_new_password && $email && $password && $new_password && $confirm_new_password)
    {
        if(login($email, $password))
        {
            if(set_password($email, $new_password))
            {
                return TRUE;
            }
        }

    }
}

If $new_password == $confirm_new_password is true, but $email is empty, you will have made an extra comparison.

As others have said, there are other ways to go about this without nesting everything, which will be functionally equivalent.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!