Operator Precedence in PHP: Ternary XOR Assignment
After writing my response on the question how to assign to multiple variables in a ternary operator I actually tried out the code I wrote:
true ? $w = 100 xor $r = 200 : $w = 300 xor $r = 400;
var_dump($w); var_dump($r);
(Don't bother it's useless, this is theoretic.)
Now, I would expect PHP to do it this way, according to operator precedence:
true ? $w = 100 xor $r = 200 : $w = 300 xor $r = 400 ;
(true) ? ( $w = 100 xor $r = 200 ) : 开发者_开发知识库( $w = 300 xor $r = 400 );
(true) ? (($w = 100) xor ($r = 200)) : (($w = 300) xor ($r = 400));
As the first part of the ternary operator is evaluated, this should output:
int 100
int 200
But instead I get
int 100
int 400
This is very odd to me, because it would require that parts of both parts of the ternary operator are executed.
Suppose it's some fault in my thinking.
aren't you just doing
(true ? $w = 100 xor $r = 200 : $w = 300) xor $r = 400;
I wouldn't use the ternary operator in this way at all. Use the ternary operator when you need the whole expression to return a value, not as a substitute for logical code constructs.
For example:
if (true) {
$w = 100;
$r = 200;
} else {
$w = 300;
$r = 400;
}
var_dump($w);
var_dump($r);
Advantages of using if/else construct:
- Easier to read, easier to maintain, easier to debug.
- Easier to add more steps inside each conditional block if the need arises.
- If you run tests using code coverage tools, you get a more accurate view of which code paths are being tested when all your code isn't on one line.
- You don't have to post a question to Stack Overflow to get it working!
Advantages of using ternary operator:
- Uses fewer curly-braces and semicolons, in case you're running out of them or can't find them on your keyboard.
精彩评论