PHP 8 Modern Syntax & Features
Match expressions, named arguments, constructor property promotion, readonly properties, enums, fibers and the JIT — the syntax that modernized PHP.
match and Nullsafe Operator
// match:严格比较(===),必须穷尽,返回值
$code = 404;
$message = match ($code) {
200, 201 => 'success',
404 => 'not found',
500 => 'server error',
default => 'unknown',
};
// nullsafe:链上任意一环为 null 则整体为 null
$city = $user?->getAddress()?->city ?? 'unknown';
// 联合类型与返回类型
function formatId(int|string $id): int|string {
return is_int($id) ? $id : strtoupper($id);
}
Constructor Promotion, Readonly and Enums
<?php
// 构造器属性提升:一行声明 + 赋值
class Point {
public function __construct(
public readonly float $x, // 只读:构造后不可变
public readonly float $y,
) {}
}
$p = new Point(1.5, 2.5);
echo $p->x; // 1.5
// 枚举(PHP 8.1+):带值的强类型枚举
enum Status: string {
case Active = 'active';
case Disabled = 'disabled';
}
$s = Status::from('active'); // 值 -> 枚举
$s->value; // 'active'
$s === Status::Active; // true
readonly plus enums make PHP DTOs nearly immutable-by-construction; pair them with promoted properties to remove boilerplate getters.
Fibers and the JIT
- Fibers (8.1) are lightweight, user-land coroutines — the foundation of async frameworks like Swoole, RoadRunner and ReactPHP.
- The JIT (8.0) compiles hot paths to machine code, speeding CPU-bound code; IO-bound web apps benefit less than expected.
- Attributes (8.0) replace doc-block annotations for declarative config in Symfony and Laravel.
match 与 nullsafe 运算符
// match:严格比较(===),必须穷尽,返回值
$code = 404;
$message = match ($code) {
200, 201 => 'success',
404 => 'not found',
500 => 'server error',
default => 'unknown',
};
// nullsafe:链上任意一环为 null 则整体为 null
$city = $user?->getAddress()?->city ?? 'unknown';
// 联合类型与返回类型
function formatId(int|string $id): int|string {
return is_int($id) ? $id : strtoupper($id);
}
构造器提升、只读属性与枚举
<?php
// 构造器属性提升:一行声明 + 赋值
class Point {
public function __construct(
public readonly float $x, // 只读:构造后不可变
public readonly float $y,
) {}
}
$p = new Point(1.5, 2.5);
echo $p->x; // 1.5
// 枚举(PHP 8.1+):带值的强类型枚举
enum Status: string {
case Active = 'active';
case Disabled = 'disabled';
}
$s = Status::from('active'); // 值 -> 枚举
$s->value; // 'active'
$s === Status::Active; // true
readonly 加枚举让 PHP 的 DTO 几乎天然不可变;配合构造器提升可以省掉大量 getter 样板。
Fiber 与 JIT
- Fiber(8.1)是轻量级用户态协程——Swoole、RoadRunner、ReactPHP 等异步框架的底层支撑。
- JIT(8.0)将热点代码编译为机器码,加速 CPU 密集逻辑;IO 密集的 Web 应用收益没有想象的大。
- Attribute(8.0)取代 doc 注解,成为 Symfony、Laravel 声明式配置的标准方式。