kenny1911 / php-clone-with
用于克隆具有其他属性的对象的辅助工具
v1.0.2
2023-08-11 08:27 UTC
Requires
- php: ^7.1 | ^8.0
Requires (Dev)
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-11 10:58:33 UTC
README
函数 Kenny1911\CloneWith\clone_with
可以在克隆过程中设置属性值。
在未来的 PHP 版本中,可能会出现一个
clone with
构造函数来解决这个问题。
使用方法
use function Kenny1911\CloneWith\clone_with; class Post { /** @var string */ private $title; /** @var string */ private $author; public function __construct(string $title, string $author) { $this->title = $title; $this->author = $author; } public function getTitle(): string { return $this->title; } public function getAuthor(): string { return $this->author; } } $post = new Post('Foo', 'Author'); $post2 = clone_with($post, ['title' => 'Bar']); echo $post2->getTitle(); // Bar
克隆 PHP 8.1 的只读属性
只读属性出现在 PHP 8.1 中。
如果使用标准的克隆对象方式(使用 clone
操作符),这些值将无法改变。
函数 clone_with
支持覆盖只读对象属性的值。
支持具有 __clone()
方法的类
类可以有 __clone()
方法,其中包含克隆对象实例的额外逻辑。
函数 clone_with
支持它,并且克隆逻辑不会被破坏。
替代方案
- spatie/php-cloneable - 一个允许你在 PHP 8.1 中克隆只读属性的
Cloneable
特性。