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