简体   繁体   中英

PHP Shorthand ternary operator “?:” Parse error unexpected “:”

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


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

Since you are using php 5.2.16, your ternary requires 2 options eg

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

Variable = condition? true value: false value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM