Is there a PHP like short version of the ternary operator in Java?

Patkos Csaba

In PHP the ternary operator has a short version.

expr1 ? expr2 : expr3;

changes into

expr1 ? : expr3;

The short version returns the result of expr1 on true and expr3 on false. This allows cool code that can populate variables based on their own current state. For example:

$employee = $employee ? : new Employee();

If $employee == null or evaluates to false for any other reason, the code above will create a new Employee(); Otherwise the value in $employee will be reassigned to itself.

I was looking for something similar in Java, but I could not find any similar use case of the ternary operator. So I am asking if is there such a functionality or something similar that can avoid one of the expressions of the ternary operator in order to reduce duplication.

NotGaeL

No, there is not. (A ternary operation requires, by definition, three operands)

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.

Source: The PHP Manual

Just like the one in Java but in Java you need to specify both outcomes:

The ternary if-else operator works with three operands producing a value depending on the truth or falsehood of a boolean assertion. It's form is as follows:-

boolean-exp ? value1 : value2

Sources:

Java specs on the ternary conditional operator

Official Java documentation

The Java.net Blogs

Also keep in mind that, unlike Java and every other popular language with a similar operator, ?: is left associative in PHP. So this:

<?php
$arg = "T";
$vehicle = ( ( $arg == 'B' ) ? 'bus' : 
             ( $arg == 'A' ) ? 'airplane' : 
         ( $arg == 'T' ) ? 'train' : 
         ( $arg == 'C' ) ? 'car' : 
         ( $arg == 'H' ) ? 'horse' : 
                               'feet' );
echo $vehicle;

prints horse instead of train (which is what you would expect in Java)

Sources:

http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/#operators

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related