PHP速记三元运算符“?:"解析错误意外的“:" [英] PHP Shorthand ternary operator "?:" Parse error unexpected ":"

查看:94
本文介绍了PHP速记三元运算符“?:"解析错误意外的“:"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将一些旧的PHP文件上传到了新服务器,并且在速记三元操作上遇到了解析错误(意外的':').例如:

$y = $x ?: "Some default";

php版本是5.2.16,这些代码简写为这些速记?:,所以在更改所有代码之前,我想我会看看是否有人对此有所了解,因为我已经有一段时间没有使用PHP了.

解决方案

仅从PHP 5.3起可用

表达式(expr1)吗? (expr2):(expr3)如果expr1评估为 TRUE ,则为expr2;如果expr1评估为 FALSE ,则为expr3.

自PHP 5.3起,可以省略三元运算符的中间部分.如果expr1评估为 TRUE ,则表达式 expr1?:expr3 返回expr1,否则返回expr3. 此示例. /p>

或更有用但在注释中请注意: http://www.php.net/manual/zh/control -structures.if.php#102060


1 http://php .net/manual/en/language.operators.comparison.php

I've just uploaded some old PHP files to a new server and am getting parse errors (Unexpected ':') on shorthand ternary ops. eg:

$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.

解决方案

This is only available since 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 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.1

See this example for more context.

or a more useful but note in the comments: http://www.php.net/manual/en/control-structures.if.php#102060


1http://php.net/manual/en/language.operators.comparison.php

这篇关于PHP速记三元运算符“?:"解析错误意外的“:"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆