PHP xor 返回错误值 [英] PHP xor returns wrong value
问题描述
使用 php 7.1.0 我正在运行这个小测试:
Using php 7.1.0 I'm running this little test:
<?php
$a = true;
$b = true;
$value = $a xor $b;
if ($value == true) {
print "bad!\n";
} else {
print "good\n";
}
它又回来说不好.为什么?两个真值的异或应该是 FALSE,而不是真.
and it's coming back and saying bad. Why? An xor of two true values should be FALSE, not true.
推荐答案
问题在于运算符优先级.xor
运算符的优先级低于 =
,因此您的语句等效于:
The problem is operator precedence. The xor
operator has lower precedence than =
, so your statement is equivalent to:
($value = $a) xor $b;
你需要写:
$value = ($a xor $b);
或
$value = $a ^ $b;
^
运算符是按位异或,而不是布尔值.但是true
和false
会被转换成1
和0
,按位的结果等价于布尔结果.但是,如果变量的原始值可能是数字,这将不起作用——所有非零数字都是真值,但是当您对它们执行按位 XOR 时,您将获得任意两个不同数字的真值结果.
The ^
operator is bit-wise XOR, not boolean. But true
and false
will be converted to 1
and 0
, and the bit-wise results will be equivalent to the boolean results. But this won't work if the original values of the variables could be numbers -- all non-zero numbers are truthy, but when you perform bit-wise XOR with them you'll get a truthy result for any two numbers that are different.
请参阅PHP 运算符优先级表
查看相关在 PHP 中使用 bool 表达式赋值:奇怪的行为
这篇关于PHP xor 返回错误值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!