2011-11-29 110 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的值。

相关问题