php 您对三元运算符使用哪种编码风格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/243217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:03:13  来源:igfitidea点击:

Which coding style you use for ternary operator?

phplanguage-agnosticcoding-styleternary-operator

提问by Imran

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?

你个人使用哪种风格,或者觉得哪种风格最易读?

Edit:(on when to use ternary-operator)

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

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.

我通常避免使用超过 2 级的深度三元运算符。当我在 PHP 模板脚本中回显变量时,我倾向于更喜欢 2 级深度三元运算符而不是 2 级 if-else。

回答by Simon Howard

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.

通过这种方式,条件和结果保持在同一行上,并且很容易浏览并了解发生了什么。

回答by Tomalak

I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.

我尽量不使用三元运算符来编写嵌套条件。它无视可读性并且没有提供比使用条件更多的价值。

Only if it can fit on a single line, and it's crystal-clear what it means, I use it:

只有当它可以放在一条线上并且它的含义非常清楚时,我才会使用它:

$value = ($a < 0) ? 'minus' : 'plus';

回答by biozinc

Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old

就我个人而言,我只使用适合一行的三元运算符。如果它需要跨越,那么是时候过去了

if else if else

回答by nickf

a style I sometimesuse, which I'm bringing up since it hasn't been mentioned, is like this:

有时使用的一种风格是这样的:

$result = ($x == y)
        ? "foo"
        : "bar";

..but usually only if putting it all on one line makes it too long. I find that having the = ? :all line up makes it look neater.

..但通常只有在将所有内容放在一行上时才会太长。我发现把= ? :所有的东西都排列起来会让它看起来更整洁。

回答by Chris Jacob

PHP nested ternary operators behave differently.

PHP 嵌套三元运算符的行为不同。

This syntax passes all the following tests. Based on http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

此语法通过了以下所有测试。基于http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');

.

.

See: http://au.php.net/ternary

见:http: //au.php.net/ternary

Example #3 "Non-obvious Ternary Behaviour" explains why the following does not work in PHP.

示例 #3 “非明显的三元行为”解释了为什么以下内容在 PHP 中不起作用。

$x = 1;
$y = 2;
$z = 3;   
$myvar = ($x == $y) 
       ? "foo" 
       : ($x == $z) 
         ? "bar" 
         : "none";  
$myvar == 'none'; // Good

$x = 1;
$y = 2;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Good

$x = 1;
$y = 1;
$z = 3;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

$x = 1;
$y = 1;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

回答by Rick Kierner

ternary operators are short effective ways to write simple if statements. They shouldn't be nested or difficult to read. Remember: You write the software once but is is read 100 times. It should be easier to read than write.

三元运算符是编写简单 if 语句的简短有效方法。它们不应嵌套或难以阅读。请记住:您编写软件一次,但会被读取 100 次。读起来应该比写起来容易。

回答by Guillaume Gervais

I tend to enclose the condition in parentheses : (a == b) ? 1 : 0

我倾向于将条件括在括号中: (a == b) ? 1 : 0

回答by John Rudy

I'll dissent with the common opinion. I'm sort of like Imran with my conditional operator style. If it fits cleanly on one line, I keep it on one line. If it doesn't fit cleanly on one line, I do break it, but I use only a single tab (4 spaces; I have VS set to insert spaces for tabs) for the indent. I don't immediately jump to if-else, because a lot of the time the conditional operator makes more sense contextually. (If it doesn't make sense contextually, however, I simply don't use it.)

我会反对一般意见。我的条件运算符风格有点像 Imran。如果它完全适合在一行上,我会将它放在一行上。如果它不能完全放在一行上,我会打破它,但我只使用一个制表符(4 个空格;我将 VS 设置为为制表符插入空格)作为缩进。我不会立即跳转到if- else,因为很多时候条件运算符在上下文中更有意义。(但是,如果它在上下文中没有意义,我就不会使用它。)

Also, I don't nest conditional operators. At that point, I do find it too difficult to read, and it's time to go to the more verbose if-elsestyle.

另外,我不嵌套条件运算符。在这一点上,我觉得它太难看了,它的时间去更详细的if-else风格。

回答by Patrick Szalapski

The ternary conditional can make code cleaner and more elegant, and most importantly, help you put emphasis on the right things and avoid repeating yourself. Consider using them, but do not make the code less readable by doing so. In VB.NET:

三元条件可以让代码更简洁、更优雅,最重要的是,帮助你把重点放在正确的事情上,避免重复自己。考虑使用它们,但这样做不会降低代码的可读性。在 VB.NET 中:

'before refactoring 
If x = 0 Then                    ' If-Then-Else puts emphasis on flow control
    label = "None"
Else
    label = Foo.getLabel(x)      '  If-Then-Else forces repeat of assignment line
End If

'after refactoring    
label = If(x = 0, "None", Foo.getLabel(x)) ' ternary If puts emphasis on assignment

Note that "it is less readable" is not the same thing as "I'm not used to seeing that".

请注意,“它的可读性较差”与“我不习惯看到它”不同。

回答by ysth

The "contrived example" is how I would indent it, except that I would indent from the left margin, not based on where the ( or whatever is on the line above.

“人为的例子”是我将它缩进的方式,除了我会从左边距缩进,而不是基于 ( 或上面一行中的任何内容。

To the ternary detractors - readability is the point. If you don't think it makes for more readable code, don't use it. But I find the contrary to be the case at least some of the time.

对于三元批评者来说 - 可读性是重点。如果您认为它不会使代码更具可读性,请不要使用它。但我发现至少在某些时候情况恰恰相反。