0

For long time I used something like this :

$foo = $foo ?: $bar; // similar to $foo = $foo ? $foo : $bar;

and it worked good.

but now I am on a new hosting with PHP Version of 5.2.17 and when I try to run similar code it shows a parse error :

Parse error: syntax error, unexpected ':' in /../

How can I solve this?

John Conde
  • 217,595
  • 99
  • 455
  • 496
John
  • 7,500
  • 16
  • 62
  • 95

2 Answers2

6

The shortened ternary syntax is only available in PHP 5.3 and newer

John Conde
  • 217,595
  • 99
  • 455
  • 496
1
Please note that the ternary operator is a statement, and that it
doesn't evaluate to a variable, but to the result of a statement. This
is important to know if you want to return a variable by reference.
The statement return $var == 42 ? $a : $b; in a return-by-reference
function will therefore not work and a warning is issued in later PHP
versions.

So there is a problem with the return-by-reference for the ?: syntax.
That's way I explicitly wrote what should be returned. 

Reference site https://groups.google.com/forum/#!msg/doctrine-user/qbSAvaKH5uI/DF_2XSxFvG4J

I can't say there was a bug with it, but from the url https://bugs.php.net/bug.php?id=60169 it seems a bug

there is also segfault in (***)?:value notation.
like:
   <?php
     $str = array('test');
     list($a, $b) = is_array($str)?:$str;

and this make *the patch doesn't work* (a memory leak)
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106