緣起
今天閱讀 Laravel 的源碼時發(fā)現(xiàn)"三元運算符"的一種簡潔寫法:
$otherKey = $otherKey ?: $instance->getKeyName();
?:
是寫在一起的!
"三元運算符"是什么?
"三元運算符"可以用一行代碼進行邏輯判斷, 從而替代常見的 if else 變量賦值判斷:
if($condition)){
$result = 'some default value';
} else{
$result = 'other default value';
}
上面的代碼用"三元運算符"來寫:
$result = $condition ? 'some default value' : 'other default value'
即 boolean_expression ? val_if_true : val_if_false
當碰到一種特殊但是常見的 if else 判斷時, 三元運算符還可以更加簡化:
"三元運算符"的簡寫
如果 "if else 變量賦值判斷"的邏輯如下:
if($variable)){
$result = $variable; //"值"和"判斷條件"是一樣的
} else{
$result = 'other default value';
}
"值"和"判斷條件"是一樣的.
通常的"三元運算符"是這樣的:
$result = $variable ? $variable : 'other default value'
簡寫的"三元運算符"是這樣的:
$result = $variable ?: 'other default value'
即 expr ? expr : val_if_false
簡寫成了 expr ?: val_if_false
注意:
- 這種寫法是在 PHP 5.3 引入的, 所以不要在之前的版本中使用;
Since PHP 5.3, it is possible to leave out the middle part of the conditional operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.- 建議不要嵌套使用"三元運算符", 因為很難理解.
跳出"三元運算符"
StackOverflow 中有個討論 Multiple conditions in the ternary operator safe?
有人將下面這種判斷簡寫成"三元運算符":
$rule1 = true;
$rule2 = false;
$rule3 = true;
if($res) {
echo "good";
} else {
echo "fail";
}
$res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true)) ? true : false;
討論中有人提到, 這種情況沒有必要使用"三元運算符", 只要寫成這樣就可以了:
$res = (($rule1 === true) && ($rule2 === false) && ($rule3 === true));
不要為了用而用.
題外
聽到"三元運算符"的概念, 感覺很高大上, 今天查英文注釋才知道 "三元" 僅僅就是指 "三個部分". 囧
"三元運算符" = Ternary operator
"ternary" = composed of three parts / 由三個部分組成
參考文章
文章歷史
- 2017/04/30 (第一次發(fā)布)
- 2017/06/05 修改潤色
- 2018/11/28 修改潤色
如果你覺得我的文章對你有用, 請打個"喜歡", 或者給些改進的建議 _