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é