spatie / php-cloneable
一个特性,允许您在PHP 8.1中克隆只读属性
1.0.2
2024-02-06 20:31 UTC
Requires
- php: ^8.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.17
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.3
README
此包提供了一个特性,允许您在PHP 8.1中克隆具有只读属性的对象。您可以在此处阅读更深入的解释,了解为什么这是必要的here。
支持我们
我们在创建一流的开源包上投入了大量资源。您可以通过购买我们的付费产品之一来支持我们。
我们非常感谢您从家乡寄来明信片,并注明您正在使用我们的哪个包。您可以在我们的联系页面上找到我们的地址。我们将在我们的虚拟明信片墙上公布所有收到的明信片。
安装
您可以通过composer安装此包
composer require spatie/php-cloneable
用法
在PHP 8.1中,只读属性一旦初始化就不允许被覆盖。这也意味着不允许克隆对象并更改其只读属性。预计PHP未来将获得某种类型的clone with
功能,但到目前为止,您可以通过使用此包来解决这个问题。
class Post { use Cloneable; public readonly string $title; public readonly string $author; public function __construct(string $title, string $author) { $this->title = $title; $this->author = $author; } }
Spatie\Cloneable\Cloneable
会将一个with
方法添加到您希望可克隆的任何类中,您可以通过传递一个或多个参数来调用它。请注意,您必须使用命名参数。
$postA = new Post(title: 'a', author: 'Brent'); $postB = $postA->with(title: 'b'); $postC = $postA->with(title: 'c', author: 'Freek');
常见的做法是在类本身上实现特定的with*
方法
class Post { // … public function withTitle(string $title): self { return $this->with(title: $title); } public function withAuthor(string $author): self { return $this->with(author: $author); } }
注意事项
- 此包在克隆对象时会跳过调用构造函数,这意味着构造函数中的任何逻辑都不会被执行。
with
方法将进行浅拷贝,这意味着嵌套的对象不会被克隆。
测试
composer test
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
贡献
有关详细信息,请参阅CONTRIBUTING。
安全漏洞
请参阅我们的安全策略,了解如何报告安全漏洞。
致谢
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。