PHP 的布尔比较处理 - 解释?
我遇到了一些让我感兴趣的事情,我只是想知道如何解释为什么会发生这种情况。
$var = true;
if($var == 'X'){
echo 'pass';
}
上面的代码会触发“pass”...为什么?如果我使用 $var === 'x'
它会按预期运行。
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
非空字符串将始终评估为
TRUE
请参阅 PHP 的关于布尔计算的文档。正如您所发现的,您必须使用===
进行严格类型比较,以测试字符串'X'
是否与布尔值TRUE
相同。A non-empty string will always evaluate to
TRUE
See PHP's documentation on boolean evaluation. As you have discovered, you must use===
for strict type comparison to test whether the string'X'
is identical to the booleanTRUE
.PHP 的类型杂耍可能有其优点,但在我看来,它会导致“危险”的误解。其他不直观的例子是:
由于各种原因,这些在 PHP 中都被认为是正确的。我总是建议编写您自己的函数来检查相等性,它会按照您的预期工作(或者您是否拥有整个 PHP 在你的脑海中输入比较矩阵?);
PHP's type juggling may have it's advantages, but in my opinion it leads to "dangerous" misunderstandings. Other examples that are not intuitiv would be:
These are all considered true in PHP for various reasons. I always recommend to write your own function to check for equality, which works as you expect it (or do you have the whole PHP type comparison matrix in your mind?);