PHP 8.1.x#
说明
本文部分内容根据官网进行删减,仅整理常用特性。
1. 新特性#
1.1 数组解包:使用字符串作为键#
添加了对使用字符串键的数组解包的支持。
<?php
$arr1 = [1, 'a' => 'b'];
$arr2 = [...$arr1, 'c' => 'd']; //[1, 'a' => 'b', 'c' => 'd']
?>
1.2 枚举的支持#
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
1.3 交叉类型#
只要能满足 class-type 的值,都可以在交集类型声明中使用,并且可使用多个值。 交集类型用 T1&T2&... 这样的语法指定。
警告:交叉类型不可与联合类型一起使用。
1.4 只读属性#
<?php
class Test {
public readonly string $prop;
public function __construct(string $prop) {
// Legal initialization.
$this->prop = $prop;
}
}
$test = new Test("foobar");
// Legal read.
var_dump($test->prop); // string(6) "foobar"
// Illegal reassignment. It does not matter that the assigned value is the same.
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>
只读属性只能初始化一次,并且只能从声明它的范围内初始化。对该属性的任何其他分配或修改都将导致错误异常。
1.5 最终类常量#
<?php
class Foo
{
final public const X = "foo";
}
class Bar extends Foo
{
public const X = "bar";
}
// Fatal error: Bar::X cannot override final constant Foo::X
?>
2. 新函数#
array_is_list():判断指定的array是否是list。如果array的key由0到count($array)-1的连续数字组成,则该数组就是list。
3. 不向后兼容的变更#
3.1 $GLOBALS 访问限制#
现在访问 $GLOBALS 数组受到一些限制。 对单个数组元素的读写访问 $GLOBALS['var'] 与之前一样。 也将继续支持对整个数组 $GLOBALS 的只读访问。 但是,不再支持对整个 $GLOBALS 数组的写访问。 例如,array_pop($GLOBALS) 将返回错误。
3.2 在继承的方法中 static 变量的用法#
当一个方法使用继承的(而不是重写的)静态变量时,继承的方法将与父级共享这个静态变量。
<?php
class A {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class B extends A {}
var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(3),之前是 int(1)
var_dump(B::counter()); // int(4),之前是 int(2)
?>
3.3 Resource 类型迁移为 Object 类型#
一些 资源(resource) 类型已被迁移到 object 类型。 要检查返回值,应该从 is_resource() 检查是否为资源,更改为检查返回值是否等于 false。
- 现在
FileInfo函数接收并返回finfo对象类型, 而不是fileinfo资源(resource) 类型。 - 现在
FTP函数接收并返回FTP\Connection对象类型, 而不是ftp资源(resource) 类型。 - 现在
IMAP函数接收并返回IMAP\Connection对象类型, 而不是imap资源(resource) 类型。 - 现在
LDAP函数接收并返回LDAP\Connection对象类型, 而不是ldap link资源(resource) 类型。 - 现在
LDAP函数接收并返回LDAP\Result对象类型, 而不是ldap result资源(resource) 类型。 - 现在
LDAP函数接收并返回LDAP\ResultEntry对象类型, 而不是ldap resultentry 资源(resource) 类型。 - 现在
PgSQL函数接收并返回PgSql\Connection对象类型, 而不是pgsql link资源(resource) 类型。 - 现在
PgSQL函数接收并返回PgSql\Result对象类型, 而不是pgsql result资源(resource) 类型。 - 现在
PgSQL函数接收并返回PgSql\Lob对象类型, 而不是pgsql large object资源(resource) 类型。 - 现在
PSpell函数接收并返回PSpell\Dictionary对象类型, 而不是pspell资源(resource) 类型。 - 现在
PSpell函数接收并返回PSpell\Config对象类型, 而不是pspell config资源(resource) 类型。
4. 废弃的功能#
4.1 实现无 __serialize() 和 __unserialize() 的 Serializable#
从 PHP 8.1.0 起,实现 Serializable 接口的类如果没有同时实现 __serialize()、__unserialize() 方法,将产生弃用警告。
4.2 不兼容从 float 到 int 的隐式转换#
从 float 隐式转换为 int 将会导致精度的丢失,目前这种行为已被废弃。 这将影响到 array 中的键、严格模式下 int 类型的声明以及对 int 的操作。
原文