多条件语句

时间:2012-07-19 11:43:46

标签: php conditional-operator

用PHP编写这个的最佳方法是什么,所以我知道哪个条件失败并且易于维护?没有诉诸多个if else语句......

if ((!$titleBlockPresent || !$leadBlock || ($allDoubleBlockCount !=2 || $allDoubleBlockCount!=1) ||$countFirstSmallShowBlocks !=2 ||$countSecondSmallShowBlocks !=2 ) && !$contentNotAvailableMessage)
{
    $this->fail("Block missing in the horizontal list of blocks on the non live carousel");
}

3 个答案:

答案 0 :(得分:1)

试试这个

$shouldFail = FALSE;
switch(TRUE){
 case !titleBlockPresent:
    echo "No title block present<br/>";
    $shouldFail = TRUE;
 case !$leadBlock:
    echo "No lead block<br/>";

  // the rest of the code
}

答案 1 :(得分:0)

如果您将该检查移到该功能中,您和其他任何查看您的代码的人都会很清楚,并且很容易维护,例如:

function tester($var1, $var2, $var3)
{
    if (!$var1) 
    {
        $this->fail("error1");
        return FALSE;
    }
    if (!$var2) 
    {
        $this->fail("error2");
        return FALSE;
    }
    if (!$var3) 
    {
        $this->fail("error3");
        return FALSE;
    }
    return TRUE;
}

您还可以为每个需要进一步说明的if添加评论。

答案 2 :(得分:0)

我想出了这个,但注意到它与GeoPhoenix的答案非常相似,反过来说,也许值得一试这个:

$bFail = false;

if(!$bFail && $contentNotAvailableMessage) $bFail = true;
if(!$bFail && !$titleBlockPresent ) $bFail = true;
if(!$bFail && !$leadBlock ) $bFail = true;

if(!$bFail && $allDoubleBlockCount != 2) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 1) $bFail = true;
if(!$bFail && $countFirstSmallShowBlocks != 2) $bFail = true;
if(!$bFail && $countSecondSmallShowBlocks != 2) $bFail = true;

if($bFail) $this->fail("Block missing in the horizontal list of blocks on the non live carousel");