嵌套速记如果

Mor*_*agh 2 php if-statement shorthand-if

如果我无法弄明白的话,我会遇到一些缺点

($product == "vindo") ? $this->getNextVindoInList($id) : $this->getNextGandrupInList($id),
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我想在该声明中进行另一次检查.像这样:

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

Tra*_*ty3 7

出于教育目的,我将完整地保留这个答案.但应该知道这不是推荐的.嵌套三元是一个坏主意.与明确的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) : ''))
Run Code Online (Sandbox Code Playgroud)

  • 这是旧的。但是有人只是点赞了它,这让我过来看看它,并想为我以前的自己打一巴掌,因为我什至把它当作一个好主意。请避免嵌套的三元组。它们不必要地难以阅读。 (2认同)