可能重複:
What are the PHP operators "?" and ":" called and what do they do?
Reference - What does this symbol mean in PHP?
我知道isset
意味着PHP。但我已經看到類似isset($x) ? $y : $z
的語法。這是什麼意思?
可能重複:
What are the PHP operators "?" and ":" called and what do they do?
Reference - What does this symbol mean in PHP?
我知道isset
意味着PHP。但我已經看到類似isset($x) ? $y : $z
的語法。這是什麼意思?
這是一個Ternary Operator,也稱爲「條件表達式操作符」(感謝奧利查爾斯沃思)。你的代碼讀取,如:
if $x is set, use $y, if not use $z
在PHP中,和許多其他語言,您可以分配基於在1行語句的條件的值。
$variable = expression ? "the expression was true" : "the expression was false".
這相當於
if(expression){
$variable="the expression is true";
}else{
$variable="the expression is false";
}
還可以嵌套這些
$x = (expression1) ?
(expression2) ? "expression 1 and expression 2 are true" : "expression 1 is true but expression 2 is not" :
(expression2) ? "expression 2 is true, but expression 1 is not" : "both expression 1 and expression 2 are false.";
這意味着,如果$x
變量沒有設置,則$y
值分配給$x
,否則價值的$z
被分配給$x
。
它是單個表達式if/else塊的簡寫。
$v = isset($x) ? $y : $z;
// equivalent to
if (isset($x)) {
$v = $y;
} else {
$v = $z;
}
該聲明將不會做任何事情的書面。
在另一方面像
$w = isset($x) ? $y : $z;
是更有意義的。如果$ x滿足isset(),則$ w被分配$ y的值。否則,$ w被分配$ z的值。
[什麼是PHP? :運算符調用,它是做什麼的?](http://stackoverflow.com/questions/1080247/what-is-the-php-operator-called-and-what-does-it-do)(以及其他幾個鏈接從[Stackoverflow PHP維基頁面](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php)。 – Quentin