PHP 新特性

PHP 8.x 带来了大量现代化特性,让代码更简洁、更安全、性能更强。

命名参数(PHP 8.0)

PHP 实例
// 传统方式:必须按顺序
array_slice($array, 1, 3, true);

// 命名参数:顺序无关,语义更清晰 array_slice(array: $array, offset: 1, length: 3, preserve_keys: true);

function createUser(string $name, int $age = 18, string $role = 'user'): string { return "$name / $age / $role"; }

echo createUser(name: '张三', role: 'admin'); // 跳过 age ``

联合类型(PHP 8.0)

`php function formatId(int|string $id): string { return (string)$id; }

function divide(int $a, int $b): int|false { if ($b === 0) return false; return intdiv($a, $b); } `

match 表达式(PHP 8.0)

`php // 比 switch 更严格(全等比较)、更简洁 $status = 2;

$label = match($status) { 1 => '待支付', 2, 3 => '处理中', // 多条件 4 => '已完成', default => '未知', };

echo $label; // 处理中 `

Nullsafe 运算符(PHP 8.0)

`php // 传统写法:层层判断 $city = null; if ($user !== null) { if ($user->getAddress() !== null) { $city = $user->getAddress()->getCity(); } }

// Nullsafe:链式调用,任一环节为 null 则整体返回 null $city = $user?->getAddress()?->getCity(); `

构造器属性提升(PHP 8.0)

`php // 传统写法 class User { public string $name; public int $age; public function __construct(string $name, int $age) { $this->name = $name; $this->age = $age; } }

// 属性提升:一行搞定声明+赋值 class User { public function __construct( public readonly string $name, public int $age = 18, private string $password = '' ) {} } `

readonly 属性(PHP 8.1)

`php class Config { public readonly string $dsn;

public function __construct(string $dsn) { $this->dsn = $dsn; // 只能赋值一次 } }

$config = new Config('mysql:host=localhost'); echo $config->dsn; // $config->dsn = 'other'; // 报错! `

枚举 Enum(PHP 8.1)

`php // 纯枚举 enum Status { case Active; case Inactive; case Deleted; }

// 带值的枚举 enum Color: string { case Red = 'red'; case Green = 'green'; case Blue = 'blue'; }

$status = Status::Active; $color = Color::Red; echo $color->value; // red

// 在函数中使用 function setStatus(Status $status): void { echo $status->name; // Active } `

交集类型(PHP 8.1)

`php interface Stringable {} interface Countable {}

// 必须同时实现两个接口 function process(Stringable&Countable $value): void { echo count($value); } `

Fibers(PHP 8.1)

`php // 轻量级协程,用于异步编程 $fiber = new Fiber(function(): void { $value = Fiber::suspend('第一次暂停'); echo '恢复,收到:' . $value; });

$result = $fiber->start(); echo $result; // 第一次暂停 $fiber->resume('hello'); // 恢复,收到:hello `

析构函数类型(PHP 8.2)

`php // DNF 类型(析取范式) function process((Stringable&Countable)|null $value): void { // ... }

// readonly 类 readonly class Point { public function __construct( public float $x, public float $y, ) {} } `

箭头函数与数组解包增强

``php // 数组解包支持字符串键(PHP 8.1) $arr1 = ['a' => 1, 'b' => 2]; $arr2 = ['b' => 3, 'c' => 4]; $merged = [...$arr1, ...$arr2]; // ['a' => 1, 'b' => 3, 'c' => 4]

// First-class callable(PHP 8.1) $fn = strlen(...); echo $fn('hello'); // 5

$arr = ['banana', 'apple', 'cherry']; usort($arr, strcmp(...));