My original idea was to discuss cloning in connection with immutable
objects, - I think it's only a serious problem in that case - but we can
bring this discussion earlier of course, as readonly properties certainly
has some effect on the clonability of objects.

When I started working on implementing immutable objects, I tried to come
up with a solution for the problem of property mutation. Actually, I even
had a short discussion with Nikita about the topic. He proposed the
following syntax (which is inspired by Rust):

public function withFoo(FooT $foo): static {
    return new static { foo => $foo, ...$this };
}

My idea was very similar, but it affects cloning:

$self = clone $this with { foo => $foo, ... }

I also tried to experiment with similar solutions to the ones proposed by
Rowan, where readonly properties were unsealed after cloning (in certain
circumstances), but my general feeling was these are not the way to go. To
be honest, I also don't really like object initializers because they omit
invoking the constructor. However, "beefing up" cloning would make sense
for me.

Given, adding support for object initializers (or a special for of it), is
also a non-trivial problem - as seen in case of the previous RFC -, and
given, the absence of this construct is not a deal-breaker for readonly
properties, I still think that it would be worth to separate the two topic
(and vote separately). This way, we can keep the current proposal
self-contained and focused. If the current vote passed, I'd certainly try
to address the problem of property mutation after cloning in the immutable
object proposal.

Regards,
Máté

Reply via email to