PHP 中的运算符优先级:三元异或赋值
在写完我对问题 如何分配到三元运算符中的多个变量 我实际上尝试了我编写的代码:(
true ? $w = 100 xor $r = 200 : $w = 300 xor $r = 400;
var_dump($w); var_dump($r);
别担心它没用,这是理论上的。)
现在,我希望 PHP 能够这样做,根据 运算符优先级:
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));
当评估三元运算符的第一部分时,应输出:
int 100
int 200
但是我得到了
int 100
int 400
这对我来说很奇怪,因为它需要执行三元运算符的两个部分的部分。
假设这是我的想法有问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不是在做吗
aren't you just doing
我根本不会以这种方式使用三元运算符。当您需要整个表达式返回值时,请使用三元运算符,而不是替代逻辑代码结构。
例如:
使用 if/else 结构的优点:
使用三元运算符的优点:
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:
Advantages of using if/else construct:
Advantages of using ternary operator: