老版本的 PHP 写一个数据传输对象,需要声明属性、写构造函数、逐个赋值,一个五个字段的类要写二十行。PHP 8 的构造器属性提升直接把这部分砍掉。

改造前后对比

<?php
// PHP 7 写法
class UserDto
{
    private int $id;
    private string $name;
    private string $email;
    private bool $active;

    public function __construct(int $id, string $name, string $email, bool $active = true)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
        $this->active = $active;
    }

    public function getId(): int { return $this->id; }
    public function getName(): string { return $this->name; }
}

// PHP 8 写法
class UserDto
{
    public function __construct(
        public readonly int $id,
        public readonly string $name,
        public readonly string $email,
        public bool $active = true,
    ) {}
}

注意几个细节:提升的属性不能重复声明;readonly 属性只能在构造函数里赋值一次;默认值必须写在参数上,不能在属性上再写一遍。

命名参数的实际价值

参数一多,位置参数就很难读。createOrder($uid, 2, 'CNY', true, false) 里的 true, false 是什么意思?命名参数让调用处自解释:

<?php
function createOrder(
    int $userId,
    int $qty,
    string $currency = 'CNY',
    bool $needInvoice = false,
    bool $giftWrap = false
): array {
    return compact('userId', 'qty', 'currency', 'needInvoice', 'giftWrap');
}

createOrder(userId: 7, qty: 2, giftWrap: true);

什么时候要谨慎

  • 公共库的 API:参数名一旦公开就成了契约,改名等于破坏兼容;
  • 与数组解包混用:...$args 之后的命名参数有顺序限制,容易踩坑;
  • 过度使用:参数超过五个,说明该用配置对象了,而不是靠命名参数让它”看起来清楚”。

配合 DTO 的实用模式

从请求数据构造对象时,用一个静态方法做校验和转换,比在控制器里散落一堆 isset 判断更整齐:

<?php
final class CreatePostInput
{
    public function __construct(
        public readonly string $title,
        public readonly string $content,
        public readonly array $tags = [],
    ) {}

    public static function fromArray(array $d): self
    {
        $title = trim((string)($d['title'] ?? ''));
        if ($title === '' || mb_strlen($title) > 120) {
            throw new InvalidArgumentException('标题不合法');
        }
        return new self($title, (string)($d['content'] ?? ''), (array)($d['tags'] ?? []));
    }
}

这样控制器只负责取参数和返回响应,校验逻辑集中在输入对象里,测试也更容易写。

本文为 PHP 学习与排错的经验整理。示例代码以通用环境为前提,请结合自身 PHP 版本与服务器配置调整;涉及生产环境的变更,建议先备份并在测试环境验证。