可能重复:
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