PHP if/else shorthand notation - multiple conditions

时间秒杀一切 提交于 2019-12-19 10:26:11

问题


Please consider the follwing code construction:

condition  ? code_if_true  : 
condition2 ? code_if_true2 : 
             code_if_false;

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

Is there a way to get this working for PHP?


回答1:


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

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

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



来源:https://stackoverflow.com/questions/14546627/php-if-else-shorthand-notation-multiple-conditions

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