← 回到首页

PHP 8.4 的 Property Hooks 比我想象的顺手

2026-05-20 · 分类:后端 · 标签:php

趁着项目重构把一处 entity 改成了 8.4 的新写法,省了一坨 getter/setter 模板。简单记一下使用感受和遇到的小细节。

之前

class User {
    public function getName(): string { return $this->name; }
    public function setName(string $name): void { $this->name = $name; }
}

之后

class User {
    public string $name {
        get => strtoupper($this->name);
        set { $this->name = trim($value); }
    }
}

局限

跟 readonly 冲突,复用时得取舍。另外 IDE 提示还不太完善,PhpStorm 还在追。