PHP if / else速记符号-多个条件 [英] PHP if/else shorthand notation - multiple conditions

查看:124
本文介绍了PHP if / else速记符号-多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码构造:

condition  ? code_if_true  : 
condition2 ? code_if_true2 : 
             code_if_false;

这不适用于PHP而适用于JavaScript。

This doesn't work for PHP whereas it does for JavaScript.

是否有一种方法可以在PHP上运行?

Is there a way to get this working for PHP?

推荐答案

在PHP中,条件运算符为 left -associative [PHP.net] ,实际上几乎所有其他语言都是右关联的。

In PHP, the conditional operator is left-associative[PHP.net], compared to virtually all other languages where it is right-associative.

为什么需要使用括号来控制求值顺序 1

That's why you need to use parentheses to control the order of evaluation1:

 condition  ? code_if_true  : 
(condition2 ? code_if_true2 : 
              code_if_false ); 

1 解析运算符的顺序,<计算操作数时,strong> 不是 。后者基本上是 未定义 [PHP.net]

1The order in which which operators are resolved, not when operands are evaluated. The latter is basically undefined[PHP.net]

这篇关于PHP if / else速记符号-多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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