2021 年 11 月 25 日,PHP 开发团队宣布正式发布 PHP 8.1,PHP 8.1 标志着 PHP 语言迎来又一波重大更新。新版本涵盖枚举、只读属性、先进的可调用语法、纤程、交集类型以及性能改进等多项功能特性,其中引入枚举成最大亮点。
PHP 8.1 新特性
枚举
此前 PHP 版本
class Status{ const DRAFT = 'draft'; const PUBLISHED = 'published'; const ARCHIVED = 'archived';}function acceptStatus(string $status) {...}PHP 8.1
enum Status{ case Draft; case Published; case Archived;}function acceptStatus(Status $status) {...}只读属性
此前 PHP 版本
class BlogData{ private Status $status; public function __construct(Status $status) { $this->status = $status; } public function getStatus(): Status { return $this->status; }}PHP 8.1
class BlogData{ public readonly Status $status; public function __construct(Status $status) { $this->status = $status; }}只读属性无法在初始化后(即被赋值之后)更改。开发者可以使用只读属性对值对象及数据传输对象进行建模。
先进的可调用语法
此前 PHP 版本
$foo = [$this, 'foo'];$fn = Closure::fromCallable('strlen');PHP 8.1
$foo = $this->foo(...);$fn = strlen(...);现在,开发者可以引用任何函数——即先进的可调用语法。
初始化器更新
此前 PHP 版本
class Service{ private Logger $logger; public function __construct( ?Logger $logger = null, ) { $this->logger = $logger ?? new NullLogger(); }}PHP 8.1
class Service{ private Logger $logger; public function __construct( Logger $logger = new NullLogger(), ) { $this->logger = $logger; }}对象现可作为默认参数值、静态变量、全局常量以及属性参数使用。这项更改使得嵌套属性成为可能。
此前 PHP 版本
class User{ /** * @Assert\All({ * @Assert\NotNull, * @Assert\Length(min=5) * }) */ public string $name = '';}PHP 8.1
class User{ #[\Assert\All( new \Assert\NotNull, new \Assert\Length(min: 6)) ] public string $name = '';}纯交集类型
此前 PHP 版本
function count_and_iterate(Iterator $value) { if (!($value instanceof Countable)) { throw new TypeError('value must be Countable'); } foreach ($value as $val) { echo $val; } count($value);}PHP 8.1
function count_and_iterate(Iterator&Countable $value) { foreach ($value as $val) { echo $val; } count($value);}当一个值需要同时满足多种约束类型时,则应使用交集类型。目前开发者还无法将交集类型与 8.0 版本中联合类型混合使用,例如 A&B|C。
Never 返回类型
此前 PHP 版本
function redirect(string $uri) { header('Location: ' . $uri); exit();}function redirectToLoginPage() { redirect('/login'); echo 'Hello'; // <- dead code}PHP 8.1
function redirect(string $uri): never { header('Location: ' . $uri); exit();}function redirectToLoginPage(): never { redirect('/login'); echo 'Hello'; // <- dead code detected by static analysis}使用 never 类型声明的函数或方法将不会返回值,且只能通过抛出异常或调用 die()、exit()、trigger_error()等情况结束脚本执行。
最终类常量
此前 PHP 版本
class Foo{ public const XX = "foo";}class Bar extends Foo{ public const XX = "bar"; // No error}PHP 8.1
class Foo{ final public const XX = "foo";}class Bar extends Foo{ public const XX = "bar"; // Fatal error}现在可以声明最终类常量,确保它们不会在子类中被覆盖。
显式八进制数字表示法
此前 PHP 版本
016 === 16; // false because `016` is octal for `14` and it's confusing016 === 14; // truePHP 8.1
016 === 16; // false because `016` is octal for `14` and it's confusing016 === 14; // true现在开发者可以使用显式 0o 前缀写入八进制数。
纤程(Fibers)
此前 PHP 版本
$httpClient->request('https://example.com/') ->then(function (Response $response) { return $response->getBody()->buffer(); }) ->then(function (string $responseBody) { print json_decode($responseBody)['code']; });PHP 8.1
$response = $httpClient->request('https://example.com/');print json_decode($response->getBody()->buffer())['code'];纤程是用于实现轻量级协作并发的原语。这种方法能够创建出如生成器般暂停并恢复代码块的方法,且可以从堆栈中的任何位置处进行。但请注意,纤程本身并不能实现并发性,而仍然需要依靠事件循环。但纤程的出现使得阻塞与非阻塞实现能够共享同一 API。
纤程让开发者摆脱以往常见于 Promiss::then()或基于生成器的样板代码。各类库大多会围绕纤程构建进一步抽象,因此大家无需直接与这种低级并发机制交互。
使用字符串键解包数组
此前 PHP 版本
$arrayA = ['a' => 1];$arrayB = ['b' => 2];$result = array_merge(['a' => 0], $arrayA, $arrayB);// ['a' => 1, 'b' => 2]PHP 8.1
$arrayA = ['a' => 1];$arrayB = ['b' => 2];$result = ['a' => 0, ...$arrayA, ...$arrayB];// ['a' => 1, 'b' => 2]PHP 之前已经支持通过扩展运算符实现数组解包,但之前只适用于包含整数键的数组。现在,这项功能也可解包字符串键数组。
性能改进
Symfony Demo App 请求时间
25 次连续运行,250 次请求(秒)(结果越低越好)

结果(相较于 PHP 8.0):
Symfony Demo 提速 23.0%
WordPress 提速 3.5%
PHP 8.1 中的性能相关变动:
面向 ARM64 的 JIT 后端(AArch64)
继承缓存(避免在各个请求中重新链接类)
快速类名解析(避免小写与哈希查找)
timelib 与 ext/date 性能改进
SPL 文件系统迭代器改进序列化/把
序列化优化
对一些内部函数做出优化 (get_declared_classes(), explode(), strtr(), strnatcmp(), dechex())
JIT 改进与修复
新的类、接口与函数
新的 #[ReturnTypeWillChange]属性。
新的 fsync 与 fdatasync 函数。
新的 array_is_list 函数。
新的 Sodium XChaCha20 函数。
弃用与向下兼容性变动
不推荐将 null 传递至不可为 null 的内部函数参数。
PHP 内置类方法中的 tentative 返回类型。
不推荐使用可序列化接口。
HTML 实体编/解码函数默认处理并替换掉单引号。
$GLOBALS 变量约束。
将 MySQLi: Default 错误模式设置为异常。
不推荐使用隐式不兼容的浮点数到整数转换。
finfo 扩展:file_info 资源迁移至现有 finfo 对象。
IMAP:imap 资源迁移至 IMAP\Connection 类对象。
FTP 扩展:Connection 资源迁移至 FTP\Connection 类对象。
GD 扩展:字体标识符迁移至 GdFont 类对象。
LDAP:资源迁移至 LDAP\Connection、LDAP\Result 以及 LDAP\ResultEntry 对象。
PostgreSQL:资源迁移至 PgSql\Connection、PgSql\Result 以及 PgSql\Lob 对象。
Pspell:pspell 与 pspell config 资源迁移至 PSpell\Dictionary 及 PSpell\Config 类对象。
PHP 近期动态
PHP 前十的地位岌岌可危
全球知名 TIOBE 编程语言社区最新发布 11 月的编程语言排行榜。据最新榜单显示,PHP 前十的地位岌岌可危。
自 20 多年前 TIOBE 指数开始发布以来,PHP 一直稳居前 10 名,然而最近它已经开始在前十的边缘苦苦挣扎。TIOBE CEO Paul Jansen 称,“尽管 PHP 曾经是 Web 编程领域的领导者,但现在它在这个领域面临着激烈的竞争。这并不是说 PHP 已经死了,仍然有很多中小型企业在依赖 PHP。
所以我预计 PHP 会进一步下降,但速度会很慢。PHP 的两个竞争对手,Ruby 和 Groovy,本月都前进了 3 个位置。具体表现为 Ruby 从第 16 位上升到第 13 位,Groovy 从第 15 位上升到第 12 位。”
最新数据显示,PHP 在 11 月份的市场占比是 1.81%, 排名从第 8 下降至第 10。两个竞争对手 Groovy 和 Ruby 在 11 月市场占比分别是 1.51%、1.43%。除此之外 Groovy 和 Ruby 的名次也有大幅提升,Groovy 从 15 名 上升到 12 名,Ruby 从 16 名上升到 13 名 。
PHP 基金会成立
11 月 22 日,PhpStorm 的开发商 JetBrains 宣布,将与 Automattic、Laravel、Laravel、Acquia 等多家公司共同成立 PHP 基金会。
公告表示,PHP 基金会将是一个非营利组织,其使命是保证 PHP 语言的生命力和繁荣。同时,该基金会将通过 Open Collective 来实现。
此外,基金会每年将筹集约 300000 美元,其中,JetBrains 将每年捐款 100000 美元,任何 php-src 的贡献者都可以向基金会申请资助。同时,当前的 RFC 流程不会改变,语言决定将始终留给 PHP Internals 社区。
PHP 基金会的网址为:





