Clone readonly properties in PHP 8.1

Overview

A trait that allows you to clone readonly properties in PHP 8.1

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This package provides a trait that allows you to clone objects with readonly properties in PHP 8.1. You can read an in-depth explanation as to why this is necessary here.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/php-cloneable

Usage

In PHP 8.1, readonly properties aren't allowed to be overridden as soon as they are initialized. That also means that cloning an object and changing one of its readonly properties isn't allowed. It's likely that PHP will get some kind of clone with functionality in the future, but for now you can work around this issue by using this package.

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;
    }
}

The Spatie\Cloneable\Cloneable adds a with method to whatever class you want to be cloneable, which you can pass one or more parameters. Note that you're required to use named arguments.

$postA = new Post(title: 'a', author: 'Brent');

$postB = $postA->with(title: 'b');
$postC = $postA->with(title: 'c', author: 'Freek');

A common practice would be to implement specific with* methods on the classes themselves:

class Post
{
    // …

    public function withTitle(string $title): self
    {
        return $this->with(title: $title);
    }

    public function withAuthor(string $author): self
    {
        return $this->with(author: $author);
    }
}

Caveats

  • This package will skip calling the constructor when cloning an object, meaning any logic in the constructor won't be executed.
  • The with method will de a shallow clone, meaning that nested objects aren't cloned as well.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
ColorJizz is a PHP library for manipulating and converting colors.

#Getting started: ColorJizz-PHP uses the PSR-0 standards for namespaces, so there should be no trouble using with frameworks like Symfony 2. ###Autolo

🔡 Portable ASCII library - performance optimized (ascii) string functions for php.

🔡 Portable ASCII Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

:clamp: HtmlMin: HTML Compressor and Minifier via PHP

🗜️ HtmlMin: HTML Compressor and Minifier for PHP Description HtmlMin is a fast and very easy to use PHP library that minifies given HTML5 source by r

Generate Heroku-like random names to use in your php applications.

HaikunatorPHP Generate Heroku-like random names to use in your PHP applications. Installation composer require atrox/haikunator Usage Haikunator is p

Extensive, portable and performant handling of UTF-8 and grapheme clusters for PHP

Patchwork UTF-8 for PHP Patchwork UTF-8 gives PHP developpers extensive, portable and performant handling of UTF-8 and grapheme clusters. It provides

PHP library to parse urls from string input

Url highlight - PHP library to parse URLs from string input. Works with complex URLs, edge cases and encoded input. Features: Replace URLs in string b

A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

:accept: Stringy - A PHP string manipulation library with multibyte support, performance optimized

🉑 Stringy A PHP string manipulation library with multibyte support. Compatible with PHP 7+ 100% compatible with the original "Stringy" library, but t

Paranoid text spacing in PHP

pangu.php Paranoid text spacing for good readability, to automatically insert whitespace between CJK (Chinese, Japanese, Korean) and half-width charac

Comments
  • Refactor GitHub Actions

    Refactor GitHub Actions

    This PR refactored the GitHub actions with the goal to make them work properly again For this all extensions have been removed from the php setup as they are not needed, removing with them all php 8.1 incompatibilities. The used php version has also been upgraded to php 8.1 as this is the minimum version for this package. The spatie/ray package has been removed as it requires ramsey/uuid which is not yet compatible with php 8.1 and makes static analysis with psalm fail.

    opened by abenerd 1
  • Fix clone iterable objects

    Fix clone iterable objects

    Hi!

    Currently, when trying to clone objects that implement the interface "\IteratorAggregate", an error occurs because "Spatie\Cloneable\Cloneable.php:13" iterates over the elements of the collection.

    With my pull request, I propose a solution to this problem.

    opened by ArtARTs36 1
Releases(1.0.0)
Owner
Spatie
We create products and courses for the developer community
Spatie
"結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件。 / "Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best PHP Chinese word segmentation module.

jieba-php "結巴"中文分詞:做最好的 PHP 中文分詞、中文斷詞組件,目前翻譯版本為 jieba-0.33 版本,未來再慢慢往上升級,效能也需要再改善,請有興趣的開發者一起加入開發!若想使用 Python 版本請前往 fxsjy/jieba 現在已經可以支援繁體中文!只要將字典切換為 bi

Fukuball Lin 1.2k Dec 31, 2022
highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages

highlight.php is a server-side syntax highlighter written in PHP that currently supports 185 languages. It's a port of highlight.js by Ivan Sagalaev that makes full use of the language and style definitions of the original JavaScript project.

Geert Bergman 633 Dec 27, 2022
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.

Motto: "Every business should have a detection script to detect mobile readers." About Mobile Detect is a lightweight PHP class for detecting mobile d

Şerban Ghiţă 10.2k Jan 4, 2023
A PHP library for generating universally unique identifiers (UUIDs).

ramsey/uuid A PHP library for generating and working with UUIDs. ramsey/uuid is a PHP library for generating and working with universally unique ident

Ben Ramsey 11.9k Jan 8, 2023
👮 A PHP desktop/mobile user agent parser with support for Laravel, based on Mobiledetect

Agent A PHP desktop/mobile user agent parser with support for Laravel, based on Mobile Detect with desktop support and additional functionality. Insta

Jens Segers 4.2k Jan 5, 2023
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

SqlFormatter A lightweight php class for formatting sql statements. It can automatically indent and add line breaks in addition to syntax highlighting

Jeremy Dorn 3.9k Jan 1, 2023
A PHP string manipulation library with multibyte support

A PHP string manipulation library with multibyte support. Compatible with PHP 5.4+, PHP 7+, and HHVM. s('string')->toTitleCase()->ensureRight('y') ==

Daniel St. Jules 2.5k Jan 3, 2023
A sane interface for php's built in preg_* functions

Making regex great again Php's built in preg_* functions require some odd patterns like passing variables by reference and treating false or null valu

Spatie 1.1k Jan 4, 2023
A fast PHP slug generator and transliteration library that converts non-ascii characters for use in URLs.

URLify for PHP A fast PHP slug generator and transliteration library, started as a PHP port of URLify.js from the Django project. Handles symbols from

Aband*nthecar 667 Dec 20, 2022
🉑 Portable UTF-8 library - performance optimized (unicode) string functions for php.

?? Portable UTF-8 Description It is written in PHP (PHP 7+) and can work without "mbstring", "iconv" or any other extra encoding php-extension on your

Lars Moelleken 474 Dec 22, 2022