Using and or in conditionals for readability instead of && ||
Often when I am writing PHP I construct conditionals like this:
if(1 === $var1
and 2 === $var2
or 1 == $var3) {
// do something here maybe
}
I think it makes them easier and more natural to read. I know this is probably laughable when I am using Yodas though.
The reason I have each condition on its own line prefaced by and
or or
is because it makes it easier to comment part of the statement out when debugging.
Is there any disadvantage to doin开发者_开发百科g this compared with the "usual" ||
and &&
?
or
and and
do not have the same operator precedence as ||
and &&
. This means that in for certain values of expressions[a]
and [b]
, [a] and [b] != [a] && [b]
. This may create non-obvious bugs.
Note that one is higher precedence than assignment, while the other is not. This is a subtle difference, and even if you understand it, other developers reading your code may not. As a result, I personally recommend using only &&
and ||
Ruby's operators are similar to PHP's in this regard. Jay Fields published a simple example of the difference.
There's no significant functional difference in PHP between and
and &&
, nor betweeen or
and ||
.
The only difference between them is that they are considered as different operators, and have different positions in the order of operator precedence. This can have a big impact on the results of complex operations if you neglect to wrap things in brackets.
For this reason, it is generally a good idea to use one or other style of operators, and stick with it, rather than mixing between the two in the same code base (this is also a good idea for readability). But the choice if which pair of operators to use is fairly immaterial.
Other than that, they are basically the same thing.
See here for the PHP operator precedence: http://php.net/manual/en/language.operators.precedence.php
(note the different positions in the table of the and
and or
vs &&
and ||
)
精彩评论