PHP 8 重大新特性完全指南

Raingad Raingad
·
·
15 阅读

PHP 8 于 2020 年发布带来了革命性的变化,本文全面解析最有价值的新特性

引言

PHP 8 是 PHP 语言历史上最重要的版本之一,带来了数百项改进全新的 JIT 编译器。无论你是 PHP 老兵还是新人,掌握这些新特性都能显著提升开发效率和代码质量。


1. 命名参数 (Named Arguments) ⭐⭐⭐⭐⭐

旧写法

htmlspecialchars($string, ENT_QUOTES, 'UTF-8', false);

PHP 8 写法

htmlspecialchars($string, double_encode: false);

优点:

  • 参数顺序无关紧要

  • 只传递必要的参数

  • 代码可读性大幅提升

Laravel 中的实际应用

// 旧写法
Route::get('/user', [UserController::class, 'index'])
    ->name('user.index')
    ->middleware('auth')
    ->middleware('verified');

// PHP 8 写法 - 更清晰
Route::get('/user', [UserController::class, 'index'])
    ->name('user.index')
    ->middleware(auth: true)
    ->middleware(verified: true);

2. 联合类型 (Union Types) ⭐⭐⭐⭐⭐

传统写法

/**
 * @param int|float $num
 * @return int|float
 */
function calculate($num) {
    return $num * 2;
}

PHP 8 写法

function calculate(int|float $num): int|float {
    return $num * 2;
}

实用的可空类型

// 之前
function getUser(?int $id): ?User { }

// PHP 8 简洁写法
function getUser(?int $id): ?User { }

// 或者使用 union
function getUser(int|null $id): User|null { }

3. Match 表达式 ⭐⭐⭐⭐

switch 的完美替代品

旧写法

switch ($status) {
    case 'pending':
        $message = '处理中';
        break;
    case 'approved':
        $message = '已通过';
        break;
    case 'rejected':
        $message = '已拒绝';
        break;
    default:
        $message = '未知状态';
}

PHP 8 写法

$message = match ($status) {
    'pending' => '处理中',
    'approved' => '已通过',
    'rejected' => '已拒绝',
    default => '未知状态',
};

优势:

  • 返回值直接赋值

  • 无需 break

  • 支持多值匹配

  • 可使用条件表达式


4. 构造函数属性提升 ⭐⭐⭐⭐⭐

旧写法

class User {
    public int $id;
    public string $name;
    public string $email;
    
    public function __construct(int $id, string $name, string $email) {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }
}

PHP 8 写法

class User {
    public function __construct(
        public int $id,
        public string $name,
        public string $email
    ) {}
}

代码减少 50%!


5. Nullsafe 运算符 ⭐⭐⭐⭐⭐

再也不用嵌套的 ternary 判断

旧写法

$country = null;
if ($user !== null) {
    if ($user->address !== null) {
        if ($user->address->country !== null) {
            $country = $user->address->country->name;
        }
    }
}

PHP 8 写法

$country = $user?->address?->country?->name;

6. 字符串函数增强 ⭐⭐⭐⭐

str_starts_with() / str_ends_with()

$url = 'https://example.com/api/users';

// 检查开头
if (str_starts_with($url, 'https://')) {
    // 安全
}

// 检查结尾
if (str_ends_with($url, '.png')) {
    // 图片文件
}

str_contains()

$email = 'user@example.com';

if (str_contains($email, '@')) {
    echo '有效的邮箱格式';
}

7. 新的 #[Attribute] 特性 ⭐⭐⭐⭐

定义属性

#[Attribute]
class Validation {
    public function __construct(
        public string $rule,
        public string $message = ''
    ) {}
}

使用属性

class User {
    #[Validation(rule: 'email', message: '邮箱格式不正确')]
    public string $email;
    
    #[Validation(rule: 'required')]
    public string $name;
}

8. JIT 编译器 ⭐⭐⭐⭐⭐

PHP 8 引入了 JIT(Just In Time)编译器,带来显著性能提升。

性能对比(官方数据)

场景

PHP 7.4

PHP 8

微基准

100%

148%

WordPress

100%

112%

启用 JIT

// php.ini
opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing

9. 错误处理改进 ⭐⭐⭐⭐

旧写法

try {
    $result = $division / $divisor;
} catch (DivisionByZeroError $e) {
    echo '不能除以零';
}

PHP 8 - 捕获多种异常

try {
    // 可能抛出多种异常的代码
} catch (InvalidArgumentException | DivisionByZeroError $e) {
    echo $e->getMessage();
}

10. New Initializers ⭐⭐⭐

现在可以在属性中使用 new 创建对象

class Config {
    public array $settings = [];
    
    public function __construct(
        public DateTime $created = new DateTime(),
        public array $options = []
    ) {}
}

实际项目升级建议

1. 逐步迁移

// 使用 #[ReturnTypeWillChange] 保持兼容性
#[ReturnTypeWillChange]
public function current() {}

2. 使用 PHPStan 静态分析

composer require --dev phpstan/phpstan
./vendor/bin/phpstan analyse app --level 8

3. 编写测试

composer require --dev phpunit/phpunit

总结

PHP 8 带来的新特性让 PHP 变得更现代、更强大:

特性

实用性

学习优先级

命名参数

⭐⭐⭐⭐⭐

必须掌握

联合类型

⭐⭐⭐⭐⭐

必须掌握

构造函数提升

⭐⭐⭐⭐⭐

必须掌握

Nullsafe

⭐⭐⭐⭐⭐

必须掌握

Match

⭐⭐⭐⭐

重点掌握

JIT

⭐⭐⭐⭐

了解即可

Attributes

⭐⭐⭐

进阶学习

评论

目录