fratily/clone-with

0.2.0 2023-11-05 12:21 UTC

This package is auto-updated.

Last update: 2024-09-05 14:06:10 UTC


README

英文README.md

fratily/clone-with 是一个 PHP 库,用于扩展对象克隆的功能。

允许在克隆对象时替换任意属性的值。即使要替换的属性是只读或私有的,这也能正常工作。

注意:目前无法替换继承自超类中的私有属性。这是基于作者的观点:“超类的私有属性应该是隐藏的,不应该从外部访问”。

用法

该库是为了使由只读属性组成的不变对象更容易使用而创建的。

class Foo {
  public function __construct(
    public readonly string $value_string,
    public readonly int $value_int,
  ) {}

  public function withString(string $new_value)
  {
    return clone_with_new_props($this, ['value_string' => $new_value]);
  }

  public function withInt(int $new_value)
  {
    return clone_with_new_props($this, ['value_int' => $new_value]);
  }
}