PHP xor 返回错误值 [英] PHP xor returns wrong value

查看:30
本文介绍了PHP xor 返回错误值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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;

^ 运算符是按位异或,而不是布尔值.但是truefalse 会被转换成10,按位的结果等价于布尔结果.但是,如果变量的原始值可能是数字,这将不起作用——所有非零数字都是真值,但是当您对它们执行按位 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆