嵌套if语句,任何可能的清理方式?

时间:2012-09-23 11:06:48

标签: php if-statement

我已经检查了一些其他问题,但他们并没有真正给我我期望的答案..

我的代码是这样的..

private function handle()
{
    if()
    {
        if(!condition)
        {
            if(!condition)
            {
                if(!condition)
                {
                    if(!condition))
                    {
                        if(!condition)
                        {
                            if(!condition)
                            {
                                if(!condition)
                                {
                                    if(!condition)
                                    {
                                        if(!condition)
                                        {
                                            code
                                        }

                                        return;
                                    }

                                    return;
                                }

                                return;
                            }

                            return;
                        }

                        return;
                    }

                    return;
                }

                return;
            }


            return;
        }

        return;
    }
}

在我看来,它是可读的但很混乱,遗憾的是我还没有找到让它看起来“漂亮”的方法。有什么想法吗?

编辑:每次回报都不同。 编辑2:给自己一个答案,谢谢大家!

4 个答案:

答案 0 :(得分:3)

条件可以由&&运算符合并。它从左到右工作,这意味着,一旦从左边开始的任何一个失败,它就会停止评估条件..

if($a) {

    if($b) {
    }

}

可以替换为

if($a && $b) {
}

答案 1 :(得分:0)

使用变量检查,或将条件组合成更少的IF语句。

可变检查如下:

$execute = TRUE;
// Opposite of what you want, e.g. if you want $a only to be TRUE, do $a !== TRUE
if (condition) {
  $execute = FALSE;
}

...
// If all the conditions were met, then everything is OK
if($execute === TRUE) {
  // code
}else {
  // return
}

编辑: 如果你想要更多地控制返回,例如,变量检查可以优选地组合IF语句。如果某个条件失败,那么特定的事情会发生,这种组合条件不能总是允许的。

答案 2 :(得分:0)

就像已发布的使用

if(condition1&&condition2){}

或者如果这不起作用,您也可以使用在条件为真时立即停止的功能

function some(){
if(!conditon 1){return 0;}
if(condition 2) {return 1;}
}

这提供了更多的权力作为第二,如果只有在第一次不满足时才有效。 您必须根据您的要求进行选择。有时虽然嵌套循环是不可避免的。

答案 3 :(得分:0)

我认为它已经找到了一个很好的方法,基本上我会为每个基本条件创建一个方法,并且我将在if语句中使用按位AND运算符(&)调用它们,不要短路。

/**
 * nonsql_condition - It means it doesn't check with the database
 *
 * sql_condition - It means it does check with the database.
 */
if(!$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition() & !$this->nonsql_condition())
{
    if(!$this->sql_condition())
    {
       return error;
    }

    if(!$this->sql_condition())
    {
       return error;
    }

    code;
}

这使我可以在我的方法中使用更少的代码行,还可以不对我的数据库进行不必要的查询。

相关问题