PHP 语法问题:问号和冒号是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1276909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP syntax question: What does the question mark and colon mean?
提问by Paul Dixon
Possible Duplicate:
quick php syntax question
可能重复:
快速 php 语法问题
return $add_review ? FALSE : $arg;
What do question mark and colon mean?
问号和冒号是什么意思?
Thanks
谢谢
回答by Paul Dixon
This is the PHP ternary operator(also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
这是 PHP三元运算符(也称为条件运算符) - 如果第一个操作数计算为真,则计算为第二个操作数,否则计算为第三个操作数。
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
将其视为可以在表达式中使用的“if”语句。在进行依赖于某些条件的简明赋值时非常有用,例如
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
还有一个速记版本(从 PHP 5.3 开始)。您可以省略中间操作数。如果为真,运算符将作为第一个操作数进行评估,否则将作为第三个操作数进行评估。例如:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with issetor a null coalescing operatorwhich is introduced in PHP7:
值得一提的是,上面的代码在使用 ie $_GET 或 $_POST 变量时会抛出未定义的索引通知,以防止我们需要使用更长的版本,带有PHP7 中引入的isset或空合并运算符:
$param = $_GET['param'] ?? 'default';
回答by Cristian Ivascu
It's the ternary form of the if-else operator. The above statement basically reads like this:
它是 if-else 运算符的三元形式。上面的语句基本上是这样的:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
有关 PHP 中三元运算的更多详细信息,请参见此处:http: //www.addedbytes.com/php/ternary-conditionals/

