编程

PHP 8.5: clone() 函数改进

12 2025-11-18 04:23:00

作为值对象的粉丝,我非常乐意尽可能将我的类和属性标记为只读,这样可以减少错误。难点在于,如果你只想更改对象的一个​​属性,你需要确保复制所有属性,就像下面的 setFirst() 函数一样。

readonly class FullName
{
    public function __construct(public string $first, public string $last)
    {
        // ..
    }

    public function setFirst(string $newFirst): FullName
    {
        return new FullName($newFirst, $this->last);
    }
}

$fullName = (new FullName("Scott", "Keck-Warren"))
    ->setFirst("Alice");

在这种情况下,只有两个属性,所以工作量不大,但添加额外的属性需要我们维护额外的步骤,这总是容易出错且令人厌烦。如果我们可以克隆对象并只更新我们需要的字段,那就太好了。

PHP 8.5 修改了克隆逻辑,因此我们可以将其变为一个带有第二个参数的函数调用,该参数包含我们想要覆盖的内容:

readonly class FullName
{
    public function __construct(public string $first, public string $last)
    {
        // ..
    }

    public function setFirst(string $newFirst): FullName
    {
        return clone($this, [
            "first" => $newFirst
        ]);
    }
}

$fullName = (new FullName("Scott", "Keck-Warren"))
    ->setFirst("Alice");