# [RFC] Property initializer for clone

- Thread: https://externals.io/message/112624
- Original archive: https://news-web.php.net/php.internals/112624
- Started by kocsismate90@gmail.com on 2020-12-27T14:19:05+00:00
- Messages: 1
- RFC: Readonly amendments (Implemented (PHP 8.3)) — https://externals.io/rfc/readonly_amendments.md
- RFC: Readonly properties 2.0 (Implemented (PHP 8.1)) — https://externals.io/rfc/readonly_properties_v2.md
- RFC: Short functions (Declined) — https://externals.io/rfc/short-functions.md
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #112624 — kocsismate90@gmail.com — 2020-12-27T14:19:05+00:00

URL: https://externals.io/message/112624#112624

Hi Internals,

I'd like to propose a new RFC which would make dealing with
immutable objects a bit easier and slightly more efficient. The RFC is
about adding support for property initializers when using clone.

In order to illustrate when this feature would be useful, let's take the
following example:

class Foo
{
    public $bar;
    public $baz;

    public function withProperties($bar, $baz)
    {
        $self = clone $this;
        $self->bar = $bar;
        $self->baz = $baz;

        return $self;
    }
}

While "with" methods are currently written the above way, my RFC would
allow to write this instead:

class Foo
{
    public $bar;
    public $baz;

    public function withProperties($bar, $baz)
    {
        return clone $this with {
            bar: $bar,
            baz: $baz,
        };
    }
}

An initial implementation is available at
https://github.com/php/php-src/pull/6538

Initially, I started working on this feature because of the feedback my
"Write-once properties" RFC got back then - namely that "write-once"
properties didn't work well with cloning -, so I wanted to circumvent this
limitation. However, I realized in the meanwhile that "clone with" would be
a nice little addition to PHP regardless of "write-once" properties, that's
why I'm proposing it separately.

Please also note that I don't want to introduce property initializers as a
general way to construct objects, so I personally have no plans to extend
this construct for the "new" operator.

Regards:
Máté
