【问题标题】:What's the best way in PHP to assign to a variable depending on two independent conditions (-> four possible values)?PHP中根据两个独立条件(->四个可能值)分配给变量的最佳方法是什么?
【发布时间】:2015-02-13 14:15:44
【问题描述】:

我有一个变量需要根据两个条件分配四个可能值之一。

目前我正在这样做:

if (conditionsOne) {
  $foo = (conditionTwo) ? 'one' : 'two';
} else {
  $foo = (conditionTwo) ? 'three' : 'four';
}

但是,恕我直言,这略微伤害了编程的“黄金法则”,即“永远不要两次编写相同的代码”(如果有人更改了 conditionTwo 并忘记更改另一个 conditionTwo,我们就有错误)。

我也可以把它写成一个嵌套的三元,但这也需要两倍的条件,而且可读性较差。

在 PHP 中有什么方法可以在不加倍代码的情况下进行这样的赋值(因此对于相同的条件不需要检查两次)并且不影响可读性?

【问题讨论】:

    标签: php boolean conditional-statements variable-assignment


    【解决方案1】:

    存储结果,并使用switch:

    $s = 0;
    
    if (conditionOne) {
      $s += 1;
    }
    if ($conditionTwo) {
      $s += 10;
    }
    
    switch ($s) {
       case 0: $foo = 'four'; break;
       case 1: $foo = 'two'; break;
       case 10: $foo = 'three'; break;
       case 11: $foo = 'one'; break;
    }
    

    【讨论】:

    • 有趣的方式!我没有这样想。
    【解决方案2】:

    应该可以...

    $values=array(array(“four”,”three”),array(“two”,”one”));
    $foo=$values[$conditionsOne][$conditionsTwo];  
    

    【讨论】:

    • 我怀疑你可以(应该?)用布尔值索引一个数组。
    • 为什么不呢?如果您正在寻找简洁的方式来编写它,那么您可以,否则使用 plain if else 或 switch
    【解决方案3】:

    我不知道这种方式是否会更好,但你可以制作一个函数并使用“return”来 优化比较:

    function cond( $conditionsOne, $conditionsTwo )
    {
        if( $conditionsOne && !$conditionsTwo ) return 'one';
        if( $conditionsOne ) return 'two';
        if( $conditionsTwo ) return 'three';
        return 'four';
    }
    
    $foo = cond( $conditionsOne, $conditionsTwo );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2015-12-14
      • 2014-05-11
      • 2015-02-05
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      相关资源
      最近更新 更多