开发者

php: $a=$b OR $a=$c vs. ternary

I need to assign one of two variables to a third variable, using the value of the second variable if the first is (bool)false or undefined.

I usually do this using ternary notation like so:

$foobar = ($some_prefix_and_some_variable_name) ? $some_prefix_and_some_variable_name : $bar ; 

but sometimes this is not so pretty if the $foo variable name is very long, as it needs to be repeated in this notation.

My question is now, is it just as good to use this notation:

$foobar = $some_prefix_and_some_variable_name OR $fooba开发者_开发问答r = $bar;

and is this notation interchangeable with the ternary version?


In PHP 5.3 there is also the short ternary notation:

$foobar = $fooooooooooooooooooooooooo ?: $bar ;


Because $foobar = $foo OR $foobar = $bar; evaluates to this:

Assign foo to foobar.
* Is there a value there?
   * If not, assign bar to foobar.

While the other evaluates to:

Is there a value at foo?
* If so assign foobar = foo
* else assign foobar = bar

In the first example, if !foo you are assigning twice, if foo it can be faster. In the second example, you are only setting the value once total. I'll wager though that the speed difference is negligible.

The bigger issue here is readability. If 5.3 short notation isn't available, then I would still use the ternary notation if only because other programmers expect it.

For that matter, you will save more time and money by using the traditional ternary syntax if only because when people see your code they won't be asking themselves, WTF?


Since PHP 5.3 there is a special operator for this:

$foobar = $fooooooooooooooooooooooooo ?: $bar;

From the documentation on the ternary operator:

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.


in matter of speed, this:

$foobar = $fooooooooooooooooooooooooo OR $foobar = $bar;

it's faster


No. I don't know for sure whether the two notations are interchangeable, which means that you should not use the second one! Whether or not they are actually the same, if it is not immediately clear what the code does (as in this case), you should change it, unless you are absolutely sure that no one else will ever have to update this code. If I saw that written, I wouldn't be sure whether it was supposed to be like this, or whether there was some typo, and the bug was simply never discovered (seen it too many times!).

Ideally, with very long variable names, you should do this:

if($fooooooooooooooooooooooooo){
    $foobar =$fooooooooooooooooooooooooo;
} else {
    $foobar = $bar;
}

Just to make it easy to read, unless speed is of the essence, in which case you should use the ternary operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜