ESC
输入关键词搜索文章
目录

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)的底层原语,大多数应用不直接使用。

其他

PHP 8.2(2022-12)

PHP 8.3(2023-11)

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());
});
// 访问属性时才触发初始化

其他

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" 模式

其他

废弃与移除速查

版本变更
8.0花括号数组访问 $arr{0} 移除
8.1向内部函数传 null 废弃(如 strlen(null)
8.2动态属性废弃
8.4隐式可空类型废弃(function test(Type $x = null)?Type $x = null

下一步