嵌套简写条件语句

3

我对一个缩写的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)
 }
}

4
注意,过度使用会导致代码难以阅读!!!此外,只有极少的性能提升,既不更快也不更慢。 - Brian
3
请不要这样做。短代码并不一定就是更好的代码。 - Sulthan
4个回答

14

出于教育目的,我会保留这个答案。但是应该知道,这是不推荐的做法。嵌套三元运算符是一个坏主意。它不提供比明确的 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
这是老旧的内容。但是有人刚刚点赞了它,这让我来看看它,并想要掴一巴掌我的以前的自己,因为我甚至把这个东西呈现为一个好主意。请避免嵌套三元运算符。它们难以阅读且没有必要。 - Travesty3

3

试试这个!

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

2
我不会使用嵌套的三元运算符来解决问题。为什么?使用明确的if/else结构的代码可以更好地传达意图,它展示了具体发生了什么。
为了几行代码而牺牲可读性是一种不明智的交换。

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

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

现在简写形式不方便,因为else语句中也有if语句。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接