【问题标题】:nested shorthand if嵌套速记 if
【发布时间】:2012-09-12 19:42:13
【问题描述】:

我无法理解的简写 if 语句有点麻烦

($product == "vindo") ? $this->getNextVindoInList($id) : $this->getNextGandrupInList($id),

这很好用,但我想在该语句中再检查一次。像这样:

if($product == "vindo") {
  if($number != 14) {
    $this->getNextVindoInList($id)
  }
} else {
 if($number != 22) {
    $this->getNextGandrupInList($id)
 }
}

【问题讨论】:

  • 小心,使用过多会导致代码难以阅读!!!它的性能提升也很小,既不快也不慢。
  • 请不要这样。短代码不是更好的代码。

标签: php if-statement shorthand-if


【解决方案1】:

出于教育目的,我将保留此答案不变。但应该知道这是不推荐。嵌套三元组是个坏主意。与显式 if-else 语句相比,它没有提供任何性能优势,并且使代码更难阅读。

也就是说,请参阅下文了解它如何可以,但不应该这样做。


两种方式:

($product == "vindo" && $number != 14 ? $this->getNextVindoInList($id) : ($number != 22 ? $this->getNextGandrupInList($id) : '')

// Equivalent of:
if ($product == "vindo" && $number != 14)
    $this->getNextVindoInList($id);
else if ($number != 22)
    $this->getNextGandrupInList($id);

// OR

// Equivalent of your example:
($product == "vindo" ? ($number != 14 ? $this->getNextVindoInList($id) : '') : ($number != 22 ? $this->getNextGandrupInList($id) : ''))

【讨论】:

  • 这是旧的。但是有人刚刚投了赞成票,这让我来看看它,并想为我以前的自己打一巴掌,甚至提出这是一个好主意。请避免嵌套三元组。它们不必要地难以阅读。
【解决方案2】:

我不会介绍带有嵌套三元运算符的解决方案。为什么?具有显式 if/else 结构的代码传达意图。它显示了到底发生了什么。

为什么要牺牲几行代码的可读性?这是一笔相当糟糕的交易。

【讨论】:

    【解决方案3】:

    您的 if 语句可以使用以下代码简化:

    if($product == "vindo" && $number != 14) {
      $this->getNextVindoInList($id)
    } else if($number != 22) {
      $this->getNextGandrupInList($id)
    }
    

    if 的排序现在不方便了,因为 else 也有一个 if 语句。

    【讨论】:

      【解决方案4】:

      试试这个!

      ($product == "vindo") ? ($number != 14 ? $this->getNextVindoInList($id) : null ) : (($number != 22) ? $this->getNextGandrupInList($id) : null)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2014-05-18
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多