PHP 8.x(8.0–8.3)带来了重大改进,使语言现代化——性能(JIT)、新的语法便利性和更强的类型检查。了解这些功能对于编写现代、地道的 PHP 以及在现代代码库中识别它们很重要。
PHP 8.0 的主要功能
php
(: , : , : );
{
{}
}
{}
= () {
, => ,
=> ,
=> ,
};
= ?->address?->city;
// Enums — first-class enumerated types (finally!)
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
}
// Readonly properties — immutable after initialization
class User { public function __construct(public readonly string $id) {} }
// First-class callable syntax
$fn = strlen(...); // create a closure from a function
// Pure intersection types: function f(A&B $x)
// Fibers (low-level async primitive)
// 8.2: readonly classes, disjunctive normal form (DNF) types, null/false/true as types
readonly class DTO { public function __construct(public string $name) {} }
// 8.3: typed class constants, #[\Override] attribute, json_validate(), dynamic class constant fetch
class Config { const string VERSION = "1.0"; } // typed constant
✓ Less boilerplate — constructor promotion, named args, match, nullsafe
✓ Stronger typing — union/intersection types, enums, readonly, typed constants
✓ Better performance — JIT, plus general engine speedups each release
✓ More expressive, safer, modern syntax overall
理解 PHP 8.x 的主要功能对于编写现代、地道的 PHP 以及在当前代码库中识别这些结构非常重要——8.x 版本代表了语言的重大现代化,大幅改进了其表达力、类型安全性和性能,帮助扭转了 PHP 过时的声誉。
许多功能现在已成为现代 PHP 中的日常工具:构造函数属性提升(消除重复的样板代码)、命名参数(可读且灵活的函数调用)、match 表达式(比 switch 更安全、返回值的替代方案)、nullsafe 操作符(?-> 用于链式调用中的简洁 null 处理)以及特别是 enums(PHP 8.1——一级枚举类型,广泛用于类型安全的常量集合)和 readonly 属性/类(用于不可变性)。
这些特性减少了样板代码、增强了类型检查,使代码更具表达力和安全性。
了解这些功能对于阅读和编写当前的 PHP 至关重要(因为现代框架和代码库广泛使用它们),对于选择地道的现代方法而不是旧的模式,以及对于理解为什么现代 PHP 是一门设计良好的能力强的语言,而不是早期声誉中的那种不一致的语言。
与语言的演变保持同步——了解每个 8.x 版本增加了什么并适当使用这些功能——是重要的知识,它区分了编写现代专业 PHP 的开发者与那些陷入过时模式的开发者,反映了对当代语言状态的掌握。