php PHP速记三元运算符“?:”解析错误意外“:”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6277222/
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 Shorthand ternary operator "?:" Parse error unexpected ":"
提问by Paul Kersey
I've just uploaded some old PHP files to a new server and am getting parse errors (Unexpected ':') on shorthand ternary ops. eg:
我刚刚将一些旧的 PHP 文件上传到新服务器,并且在速记三元操作中遇到解析错误(意外的“:”)。例如:
$y = $x ?: "Some default";
php version is 5.2.16 The code is littered with these shorthand ?:, so before changing them all I thought I'd see if anyone knows anything about this as I've not used PHP for a while now.
php 版本是 5.2.16 代码中充斥着这些简写?:,所以在更改它们之前,我想看看是否有人对此有所了解,因为我已经有一段时间没有使用 PHP了。
回答by azat
This is only available since PHP 5.3
这仅自 PHP 5.3 起可用
The expression (expr1) ? (expr2) : (expr3)evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.1
表达式(expr1) ? (expr2) : (expr3)如果 expr1 评估为TRUE则评估为 expr2 ,如果 expr1 评估为FALSE则 expr3 。
自 PHP 5.3 起,可以省略三元运算符的中间部分。表达式expr1 ?: expr3如果 expr1 的计算结果为TRUE则返回 expr1 ,否则返回expr3 。1
See this examplefor more context.
有关更多上下文,请参阅此示例。
or a more useful but note in the comments: http://www.php.net/manual/en/control-structures.if.php#102060
或者在评论中更有用但请注意:http: //www.php.net/manual/en/control-structures.if.php#102060
1http://php.net/manual/en/language.operators.comparison.php
1 http://php.net/manual/en/language.operators.comparison.php
回答by Nightwolf
Since you are using php 5.2.16, your ternary requires 2 options e.g
由于您使用的是 php 5.2.16,因此您的三元需要 2 个选项,例如
$y = $x? "???" : "Some default";
Variable = condition ? true value : false value ;
变量 = 条件 ? 真值:假值;