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

有些话、适合烂在心里 提交于 2020-01-13 10:43:35

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/27387777/is-there-a-php-like-short-version-of-the-ternary-operator-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!