PHP中是否有像三元运算符短版本的PHP? [英] Is there a PHP like short version of the ternary operator in Java?

查看:145
本文介绍了PHP中是否有像三元运算符短版本的PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,三元运算符的版本较短。

In PHP the ternary operator has a short version.

expr1 ? expr2 : expr3;

变为

expr1 ? : expr3;

短版本返回expr1的结果为true,expr3的结果为false。
这允许很酷的代码可以根据自己的当前状态填充变量。例如:

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();

如果 $ employee == null 或评估由于任何其他原因为false,上面的代码将创建一个 new Employee(); 否则 $ 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.

我在Java中寻找类似的东西,但我找不到任何类似的三元运算符用例。所以我想问是否有这样的功能或类似的东西可以避免三元运算符的一个表达式,以减少重复。

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.

推荐答案

不,没有。 (三元操作需要按照定义,三个操作数)

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


从PHP 5.3开始,可以省略
三元运算符的中间部分。表达式expr1?:expr3如果expr1
的计算结果为TRUE则返回expr1,否则返回expr3。

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.

来源: PHP手册

就像在Java中但在Java中你需要指定两个结果:

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


三元
if-else运算符与三个一起工作操作数产生一个值,取决于
对布尔断言的真或假。它的形式如下:
如下: -

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

来源:

< a href =http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25\"rel =noreferrer>关于三元条件运算符的Java规范

官方Java文档

Java.net博客

还要记住,与Java和其他类似运算符的其他流行语言不同,?:在PHP中保持关联。所以这个:

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;

打印而不是 train (这是你在Java中所期望的)

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

来源:

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

这篇关于PHP中是否有像三元运算符短版本的PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆