Understanding PHP type coercion(了解 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.
这篇关于了解 PHP 类型强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:了解 PHP 类型强制


- PHP Count 布尔数组中真值的数量 2021-01-01
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01