简体   繁体   中英

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.

你不只是在做

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM