PHP 将数字解释为浮点数,即使它们小于 INT_MAX
PHP interprets numbers as floats even when they're less than INT_MAX
PHP 文档 here 指出:
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
但是结果小于 PHP_INT_MAX 的操作呢?
以这段代码为例:
$max_int = 2**31-1 ; // 2147483647
var_dump(PHP_INT_MAX === $max_int); // false
如您所见,即使操作产生有效的 int 值 PHP 似乎也将结果转换为 float
var_dump(PHP_INT_MAX === (int) $max_int) // true
我的问题:
PHP 解释器在进行任何计算之前是否将结果转换为浮点数?
不应该PHP计算结果然后相应地设置类型吗? (有道理吗?)
编辑:
PHP 版本:7.2.1 32 位
OS: Windows: 10 x64
我正在使用 XAMPP
计算 $max_int = 2**31-1
时,引擎按以下步骤执行此操作:
$tmp = 2**31;
$max_int = $tmp-1
此处$tmp
大于最大整数值并转换为浮点数。结果是有一个浮点数减法,结果是一个浮点数。因为它一直是浮动的,所以它必须保持浮动。
PHP 文档 here 指出:
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.
但是结果小于 PHP_INT_MAX 的操作呢?
以这段代码为例:
$max_int = 2**31-1 ; // 2147483647
var_dump(PHP_INT_MAX === $max_int); // false
如您所见,即使操作产生有效的 int 值 PHP 似乎也将结果转换为 float
var_dump(PHP_INT_MAX === (int) $max_int) // true
我的问题:
PHP 解释器在进行任何计算之前是否将结果转换为浮点数?
不应该PHP计算结果然后相应地设置类型吗? (有道理吗?)
编辑:
PHP 版本:7.2.1 32 位
OS: Windows: 10 x64
我正在使用 XAMPP
计算 $max_int = 2**31-1
时,引擎按以下步骤执行此操作:
$tmp = 2**31;
$max_int = $tmp-1
此处$tmp
大于最大整数值并转换为浮点数。结果是有一个浮点数减法,结果是一个浮点数。因为它一直是浮动的,所以它必须保持浮动。