Does PHP exist as a short version of the ternary operator in Java?

In PHP, the ternary operator has a short version.

expr1 ? expr2 : expr3; 

changes to

 expr1 ? : expr3; 

The short version returns expr1 to true and expr3 to false. This allows you to use cool code that can populate variables depending on their current state. For instance:

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

If $employee == null or false for any other reason, the code above will create 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 a similar example of using a ternary operator. So I ask if there is such functionality or something similar that avoids one of the ternary operator expressions in order to reduce duplication.

+5
source share
1 answer

No no. (For a triple operation, by definition , three operands are required)

Starting with PHP 5.3, you can exclude the middle part of the ternary operator. The expression expr1 ?: Expr3 returns expr1 if expr1 is TRUE and expr3 otherwise.

Source: PHP Guide

As in Java, but in Java you need to specify both results:

Triple if-else works with three operands that produce a value depending on the truth or false of a boolean statement. This form is as follows: -

 boolean-exp ? value1 : value2 

Sources:

Java specs for a ternary conditional statement

Java official documentation

Java.net Blogs

Also keep in mind that, unlike Java and any other popular language with a similar operator, ?: Remains associative in PHP. So:

 <?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 (as you would expect in Java)

Sources:

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

+10
source

Source: https://habr.com/ru/post/1208685/


All Articles