你使用三元运算符的编码风格? [英] Which coding style you use for ternary operator?

查看:155
本文介绍了你使用三元运算符的编码风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保持在单行,如果它的短。最近我一直使用这种风格更长或嵌套的三元运算符表达式。一个假设的例子:

I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:

$value = ( $a == $b ) 
            ? 'true value # 1'
            : ( $a == $c )
                ? 'true value # 2'
                : 'false value';

个人认为您使用哪种风格或最容易阅读?

Personally which style you use, or find most readable?

编辑: (在何时使用三元运算符)

(on when to use ternary-operator)

比2级深三元运算符。我倾向于喜欢2级深三元运算符超过2级如果 - 否则,当我回应PHP模板脚本中的变量。

I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.

推荐答案

三元运算符通常是要避免的,但是这种形式是可读的:

The ternary operator is generally to be avoided, but this form can be quite readable:

  result = (foo == bar)  ? result1 :
           (foo == baz)  ? result2 :
           (foo == qux)  ? result3 :
           (foo == quux) ? result4 : 
                           fail_result;

这样,条件和结果保存在同一行,撇下并了解发生了什么。

This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.

这篇关于你使用三元运算符的编码风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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