尝试访问数组时,从 float 到 int 的隐式转换会丢失精度

Implicit conversion from float to int loses precision when trying to access array

所以这里的错误信息很简单,但我不明白为什么会这样。刚刚升级到 PHP 8 并尝试修复弃用问题。

我有 $object 看起来像这样(所有字符串键):

Array
(
    [a] => ABC
    [b] => 599.97
    [c] => 0.00
    [d] => 50
    [e] => Test
)

我有 $field,当我有 var_dump($field) 我得到 float(1.05)

在我的代码中发生了以下情况:我想检查 $field 是否是 $object 的有效键。如果是,我想使用通过键访问的值,如果不是,我想使用 $field 作为值。

所以我有以下代码:

$a = $object[$field] ?? $field;

然而正是这一行代码触发了以下警告:

DEPRECATED | PID: 6978 | CODE: 8192 | MESSAGE: Implicit conversion from float 1.05 to int loses precision

我认为这可能与空合并有关,但这段代码也触发了相同的警告:

$a = $object[$field];

请注意$a这里只是一个随机的替代未使用变量,我没有在其他任何地方输入提示或声明,当我使用这个虚拟变量时,警告仍然出现。

为什么会这样?这里如何隐式转换为 int ?试图解决这个问题让我发疯。

来自manual(强调我的)-

Additionally the following key casts will occur:

...

Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.

...

在PHP 中,数组的键可以是整数或字符串。所有其他类型都需要转换为其中一种。

当您执行 $object[1.05] 时,它会在内部将此值转换为 int,因此它会执行 $object[1],但此行为可能会产生误导,因此自 PHP 8.1 起您会收到警告。