这是使用IF()更有效,更简单或嵌套的条件


which is more efficient, simple or nested condition using IF()

我是个新手,只是想问一下编程方面的问题。我希望你们能帮我理解:)

在这两个函数之间哪个在编码和性能上更有效?第一个函数使用嵌套条件,第二个函数使用简单条件,哪一个实施起来更好?

function optionOne()
{
    $a = getData();
    $return = array();
    if ($a === false) {
        $return['error'] = true;
    } else {
        $b = getValue();
        if ($b === false) {
            $return['error'] = true;
        } else {
            $c = getVar();
            if ($c === false) {
                $return['error'] = true;
            } else {
                $return['error'] = false;
                $return['message'] = 'congrat!';
            }
        }
    }
    return $return;
}
function optionTwo()
{
    $return = array();
    $a = getData();
    if ($a === false) {
        $return['error'] = true;
        return $return;
    }
    $b = getValue();
    if ($b === false) {
        $return['error'] = true;
        return $return;
    }
    $c = getVar();
    if ($c === false) {
        $return['error'] = true;
        return $return;
    } else {
        $return['error'] = false;
        $return['message'] = 'congrat!';
    }
    return $return;
}

谢谢大家,

function option()
{
 $return=array();
 $return['error'] = true;
 switch(getData()){
 case false:
 return $return;
 break;
 case true:
 if(getValue()==false){return $return;}
 else{
 if(getVar()==false){return $return;}
 else{
 $return['error'] = false;
 $return['message'] = 'congrat!';}
 }
 break;
 default:
 return 'getData() return null value';
 break;
 }
}

尝试将switch方法应用于您的函数,作为您的选项之一

一个更简洁的选择是让这3个函数在出现错误时抛出异常,而不是返回布尔值false。这就是例外的作用。然后在你的函数中,你可以把调用包装在try-catch块中。

function option {
  $return = array();
  try {
    $a = getData();
    $b = getValue();
    $c = getVar();
    $return['error'] = false;
    $return['message'] = 'congrat!';
  } catch(Exception e) {
    $return['error'] = true;
  }
  return $return;
}