Php 嵌套速记if
我对一份我搞不懂的缺少人手的if声明有点麻烦Php 嵌套速记if,php,if-statement,shorthand-if,Php,If Statement,Shorthand If,我对一份我搞不懂的缺少人手的if声明有点麻烦 ($product == "vindo") ? $this->getNextVindoInList($id) : $this->getNextGandrupInList($id), 这很好,但我想在声明中再检查一次。像这样: if($product == "vindo") { if($number != 14) { $this->getNextVindoInList($id) } } else { if($num
($product == "vindo") ? $this->getNextVindoInList($id) : $this->getNextGandrupInList($id),
这很好,但我想在声明中再检查一次。像这样:
if($product == "vindo") {
if($number != 14) {
$this->getNextVindoInList($id)
}
} else {
if($number != 22) {
$this->getNextGandrupInList($id)
}
}
试试这个
($product == "vindo") ? ($number != 14 ? $this->getNextVindoInList($id) : null ) : (($number != 22) ? $this->getNextGandrupInList($id) : null)
出于教育目的,我将保留此答案。但是应该知道,这是不推荐的。筑巢是个坏主意。与显式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) : ''))
可以使用以下代码简化if语句:
if($product == "vindo" && $number != 14) {
$this->getNextVindoInList($id)
} else if($number != 22) {
$this->getNextGandrupInList($id)
}
sorthand if现在不方便使用,因为else也有if语句。我不会用嵌套的三元运算符给出解决方案。为什么?带有显式if/else结构的代码传达了意图。它显示了到底发生了什么
为什么要牺牲几行的可读性?这是一个相当糟糕的交易。小心,使用太多会导致代码更难阅读!!!它的性能增益也很小,既不快也不慢。请不要这样做。短代码不是更好的代码。这是旧代码。但有人刚刚投了更高的票,这让我来看看它,并想扇我以前的自己一巴掌,因为我甚至把它作为一个好主意。请避免嵌套三元组。它们不必要地难以阅读。