match:干掉一长串 switch

旧写法:

switch ($status) {
    case 'pending':
        $label = '待支付';
        break;
    case 'paid':
        $label = '已支付';
        break;
    default:
        $label = '未知';
}

PHP 8 之后:

$label = match ($status) {
    'pending' => '待支付',
    'paid'    => '已支付',
    'refund'  => '已退款',
    default   => '未知',
};

三个好处:严格比较(== 变 ===)、有返回值、漏写分支直接报错(没有 default 且不匹配时抛 UnhandledMatchError)。

枚举:把状态从常量里解放出来

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Refunded = 'refunded';

    public function label(): string
    {
        return match ($this) {
            self::Pending => '待支付',
            self::Paid => '已支付',
            self::Refunded => '已退款',
        };
    }

    public static function options(): array
    {
        return array_column(
            array_map(fn ($case) => ['value' => $case->value, 'label' => $case->label()], self::cases()),
            'label',
            'value'
        );
    }
}

在 Laravel 里可以直接配合 Eloquent 转换:

protected $casts = [
    'status' => OrderStatus::class,
];

之后 $order->status 拿到的是枚举实例,$order->status->label() 直接取中文,避免在 Blade 里写一堆 @if。

只读属性与只读类

final class Money
{
    public function __construct(
        public readonly int $amount,
        public readonly string $currency = 'CNY',
    ) {}

    public function add(Money $other): self
    {
        return new self($this->amount + $other->amount, $this->currency);
    }
}

readonly 保证值对象不可变,避免了「传引用被下游改掉」的问题。PHP 8.2 起还可以直接 readonly class,一次性给所有属性加只读。

命名参数让调用更可读

// 之前
$pdf->render(true, false, 20);

// 之后
$pdf->render(withHeader: true, withFooter: false, fontSize: 20);

配合构造函数里的可选参数特别好用,尤其是写测试的时候。

需要注意的兼容性问题

  • match 是严格比较,match ('1') 不会命中 1 分支;
  • 枚举不能继承,也不能有动态属性;
  • readonly 属性只能在声明它的作用域初始化一次,clone 后需要重新赋值要小心。

小结

特性 适合替换
match switch / 多层 if-else 映射
enum 状态常量类 + 文案映射
readonly DTO、值对象
命名参数 参数多的工具方法
本文由 Devin 整理发布于 IT 笔记, 采用 CC BY-NC-SA 4.0 许可协议, 转载请注明出处。