PHP 8.x 新特性
PHP 8.0 至 8.5(2020–2025)带来了语言层面的系统性革新。本页按版本梳理改变了日常编码方式的关键特性。
PHP 8.0(2020-11)
PHP 8.0 是一个里程碑版本,引入了 JIT 编译器和多项语法改进。
Named Arguments
// 按名称传递参数,可跳过可选参数
htmlspecialchars($string, double_encode: false);
array_fill(start: 0, count: 100, value: 50);
Match 表达式
$code = 404;
$message = match($code) {
200, 301 => 'Success',
404 => 'Not Found',
default => 'Unknown',
};
// 严格比较(===),无 fall-through,返回值可赋值
Nullsafe Operator
// 链式调用中任一环节为 null 则整体返回 null
$country = $user?->address?->country ?? 'Unknown';
Union Types
function id(int|string $value): int|string {
return $value;
}
Constructor Property Promotion
class User {
public function __construct(
public string $name,
public int $age = 0,
) {}
}
JIT Compiler
Just-In-Time 编译器将 PHP 字节码编译为机器码,CPU 密集型任务性能提升约 2 倍。通过 opcache.jit=1255 启用。
PHP 8.1(2021-11)
Enums(枚举)
enum Color: string {
case Red = 'red';
case Green = 'green';
case Blue = 'blue';
}
function paint(Color $c): void { ... }
paint(Color::Red);
Readonly Properties
class Point {
public function __construct(
public readonly float $x,
public readonly float $y,
) {}
}
$p = new Point(1.0, 2.0);
// $p->x = 3.0; // Error: readonly
Fibers
$fiber = new Fiber(function (): void {
$received = Fiber::suspend('from fiber');
echo "Got: {$received}";
});
$value = $fiber->start(); // 'from fiber'
$fiber->resume('hello'); // Got: hello
Fiber 是 async/await 框架(Swoole、ReactPHP)的底层原语,大多数应用不直接使用。
其他
- Intersection Types:
A&B同时满足两个类型 - Never Return Type:
function abort(): never表示永不返回 - First-class Callable Syntax:
strlen(...)获取函数引用
PHP 8.2(2022-12)
- Readonly Classes:
readonly class User { ... }所有属性自动 readonly - DNF Types:
(A&B)|null交集与联合的组合 - True/False/Null 独立类型:
function test(): true - Dynamic Properties 废弃: 不再允许动态创建属性,需用
#[\AllowDynamicProperties]豁免 - New Random Extension: 替代老化的
mt_rand(),提供密码学安全的随机数
PHP 8.3(2023-11)
- Typed Class Constants:
const string NAME = 'test'; - #[\Override] Attribute: 编译期检查方法是否确实覆盖了父类方法
- json_validate(): 验证 JSON 字符串合法性(不解析为变量)
- Readonly Amend: 匿名类可标记 readonly,readonly 属性克隆时可重新初始化
PHP 8.4(2024-11)
Property Hooks
class User {
public string $fullName {
get => $this->firstName . ' ' . $this->lastName;
}
public string $firstName {
set => ucfirst(strtolower($value));
}
}
Asymmetric Visibility
class Config {
public protected(set) string $theme; // 外部可读,类内可写
}
Lazy Objects
$reflector = new ReflectionClass(Heavy::class);
$object = $reflector->newLazyGhost(function (Heavy $ghost): void {
$ghost->__construct(fetchExpensiveData());
});
// 访问属性时才触发初始化
其他
- #[\Deprecated] Attribute: 标记函数/方法为废弃,触发
E_USER_DEPRECATED - HTML5 DOM Parser: DOM 扩展默认使用 HTML5 解析器
- New without parentheses:
new Foo()->method()不再需要括号
PHP 8.5(2025-11)
Pipe Operator
$title = ' PHP 8.5 Released ';
$slug = $title
|> trim(...)
|> strtolower(...)
|> str_replace('.', '-', ...);
// 从左到右链式传递,替代嵌套调用
URI Extension
use Uri\Rfc3986\Uri;
$uri = new Uri('https://php.net/releases/8.5/en.php');
echo $uri->getHost(); // php.net
echo $uri->getPath(); // /releases/8.5/en.php
内置 URI 解析扩展,替代老旧的 parse_url(),遵循 RFC 3986 和 WHATWG URL 标准。
Clone With
$original = new User(name: "Alice", age: 25);
$copy = clone($original) with { name: "Bob" };
// 简化 readonly 类的 "with-er" 模式
其他
- #[\NoDiscard]: 标记返回值必须被使用,防止 API 调用遗漏
- Persistent cURL Handles: cURL 句柄跨请求持久化
- Closures in Constant Expressions: 静态闭包可用于属性参数
废弃与移除速查
| 版本 | 变更 |
|---|---|
| 8.0 | 花括号数组访问 $arr{0} 移除 |
| 8.1 | 向内部函数传 null 废弃(如 strlen(null)) |
| 8.2 | 动态属性废弃 |
| 8.4 | 隐式可空类型废弃(function test(Type $x = null) → ?Type $x = null) |