了解 PHP 类型强制
我看到了这么一小段代码,让我无法理解:
I saw this small piece of code that is evading my understanding:
<?php
$a = '0e462097431906509019562988736854';
$b = '0e830400451993494058024219903391';
var_dump($a == $b);
将输出:
bool(true)
我了解当使用 ==
时,PHP 会尝试模糊比较,在类型之间静默转换以执行比较.我不理解的是为什么 PHP 似乎认为这两个字符串是相同的.我会认为由于 $a
和 $b
是字符串,因此不需要进行类型转换.
I understand that when using ==
, PHP will attempt fuzzy comparison, silently converting between types in order to perform the comparison. What I'm not understanding is why PHP seems to think these two strings are the same. I would have thought since $a
and $b
are strings, that no type conversion would need to take place.
我不明白什么?
推荐答案
我觉得这篇文章解释的很好:
I think this article explains it pretty well:
类型强制比较运算符会将数字字符串转换为数字
在这里引用主要问题:
根据php language.operators.comparison,类型强制比较运算符会强制如果它们看起来都像数字,则两个浮点数的操作数,即使它们都已经是字符串:
According to php language.operators.comparison, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings:
两个字符串都使用指数符号,因此被视为数字字符串,进行松散比较(==
),强制这些字符串在实际松散"之前浮动比较它们.
where both strings are using exponential notation, hence are treated as numeric strings, making loose comparison (==
), coerce these strings to floats before actually "loosely" comparing them.
作为最佳实践并防止意外行为,请始终尝试使用 身份平等(===
),尤其是在处理字符串时.
As a best practice and to prevent unexpected behaviour, always try to use identity equality (===
), especially when dealing with strings.
相关文章