编程

PHP 8.5: 弃用非规范标量类型的强制转换(boolean|double|integer|binary)

33 2025-08-09 00:39:00

PHP 标量类型的强制转换允许使用标量类型的一些变体来使用。例如,既可以使用 (integer),也可以使用 (int) 将变量强制转换为整数:

$value = '42';

(integer) $value; // int(42)
(int) $value; // int(42)

PHP 标量类型有如下这些可替代的变体:

类型规范类型名备选类型名称
Integer(int)(integer)
Float(float)(double)
Boolean(bool)(boolean)
String(string)(binary)

备用类型名称不支持参数,返回值或属性类型:

function test(integer $value): double {}
Warning: "double" will be interpreted as a class name. Did you mean "float"? Write "\double" to suppress this warning in ... on line ...

Warning: "integer" will be interpreted as a class name. Did you mean "int"? Write "\integer" to suppress this warning in ... on line ...

由于存在这样的不一致性,PHP 8.5 弃用了上述 4 种备选标量类型名称。

在 PHP 8.5 以上的 PHP 8.x 系列版本中,使用这些弃用的强制类型转换将会发出弃用通知:

(integer) $value
Deprecated: Non canonical cast (integer|boolean|double|binary) is deprecated, use the (int|bool|float|string) cast instead

自 PHP 9.0 及以上版本,PHP 8.5 将不再识别这些强制类型转换: (integer|boolean|double|binary),而会将其视为强制转换为同名的类。

建议更换

为避开弃用,请将强制转换替换为规范标量类型:

 -(integer) $value; // int(42)
 +(int) $value;     // int(42)

 -(double) $value; // float(42)
 +(float) $value;  // float(42)

 -(boolean) $value; // bool(true)
 +(bool) $value;    // bool(true)

 -(binary) $value; // string(3) "foo"
 +(string) $value; // string(3) "foo"

向后兼容性影响

这一变更为备用标量类型的每次强制转换操作引入了新的弃用通知。这是在执行时发出的;不是在编译的时候。

用规范标签替换弃用的标量类型名称是一种向后兼容的修复方法。

 

下一篇