【发布时间】:2012-01-09 06:12:08
【问题描述】:
可能重复:
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,也称为“条件表达式运算符”(感谢 Oli Charlesworth)。您的代码如下所示:
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 的值。
【讨论】: