编写此逻辑的最简单方法

时间:2021-01-25 20:23:16

标签: php

我正在编写一个调用两个可为空的布尔 API 的函数。如果任一 API 返回 true,则我的函数应返回 true。如果两者都返回 false,我的函数应该返回 false。否则,我的函数应该返回 null。换句话说:

true, true -> true
true, false -> true
true, null -> true
false, false -> false
false, null -> null
null, null -> null

有没有一种简单/优雅的方式来写这个?显然,像这样的 if-else 链可以工作,但我认为它相当混乱,特别是因为您必须考虑 null 是一个虚假值。

if ($cond1 || $cond2) {
    return true;
} else ($cond1 === false && $cond2 === false) {
    return false;
} else {
    return null;
}

6 个答案:

答案 0 :(得分:4)

坚持你的建议。改进的一点是您在返回后不需要 if - else 分支。你只需要两个if

function evaluate(?bool $cond1, ?bool $cond2): ?bool
{
    if ($cond1 || $cond2) {
        return true;
    }
    if ($cond1 === false && $cond2 === false) {
        return false;
    }
    return null;
}

答案 1 :(得分:0)

怎么样

return ($cond1 ? $cond1 : $cond2);

答案 2 :(得分:0)

您可以像这样删除 else if 块:

if ($cond1 || $cond2) {
    return true;
}

return !isset($cond1, $cond2) ? null : false; 

您可以将其简化为:

return ($cond1 || $cond2) ? true : (!isset($cond1, $cond2) ? null : false)

但这很难读懂,也很难理解。

答案 3 :(得分:0)

怎么样:

if($cond1 === true || $cond2 === true){ 
 return true; 
}else{ //check first and sec cond for falsing
    if($cond1 === false && $cond2 === false){
      return false; 
    }else{ //else null it
      return null; 
    }
}

答案 4 :(得分:0)

根据您的规定(并假设每个参数是以下之一:null、true 或 false),您可以减少 smidgeon:

function foo($a, $b) {
    if($a || $b)                    return true;
    if([$a, $b] === [false, false]) return false;
}

答案 5 :(得分:0)

以下似乎有效,我尝试使用 Javascript 进行逻辑处理,如下图所示

  function testMyConditions($c1, $c2) {
      return ($c1 === true || $2 === true) ? true:  ($c1 === null || $c2 === null ? null: false)
    }

function testMyConditions($cond1, $cond2) {
  return ($cond1 === true || $cond2 === true) ? true:  ($cond1 === null || $cond2 === null ? null: false)
}

function runTests($cond1, $cond2, $expected) {
  console.log($cond1,  $cond2, $expected, $expected === testMyConditions($cond1, $cond2) ? '=> OK': '=> NOT OK')
}

runTests(true, true, true)
runTests(true, false, true)
runTests(true, null, true)
runTests(false, false, false)
runTests(false, null, null)
runTests(null, null, null)