2011-11-29 109 views
1

可能重複:
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的語法。這是什麼意思?

+0

[什麼是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

回答

8

這是一個Ternary Operator,也稱爲「條件表達式操作符」(感謝奧利查爾斯沃思)。你的代碼讀取,如:

if $x is set, use $y, if not use $z 
+3

哈,這是你第二次打我10秒回答。 – brianreavis

+1

它更準確地稱爲「條件表達式運算符」。 –

+0

感謝您的回答:) – John

2

在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."; 
0

這意味着,如果$x變量沒有設置,則$y值分配給$x,否則價值的$z被分配給$x

0

它是單個表達式if/else塊的簡寫。

$v = isset($x) ? $y : $z; 

// equivalent to 
if (isset($x)) { 
    $v = $y; 
} else { 
    $v = $z; 
} 
2

該聲明將不會做任何事情的書面。

在另一方面像

$w = isset($x) ? $y : $z; 

是更有意義的。如果$ x滿足isset(),則$ w​​被分配$ y的值。否則,$ w被分配$ z的值。

相關問題