On Wed, Jun 11, 2025, at 17:34, Tim Düsterhus wrote:
> Hi
> 
> Am 2025-06-08 21:15, schrieb Rob Landers:
> > So, it seems like this can only be used for things that can already be 
> > cloned?
> 
> Yes. It's an extension of the existing cloning functionality.
> 
> > Things which are directly trying to block an identical clone, but would 
> > otherwise be fine with a clone that changes the value (e.g. value 
> > objects) aren’t allowed to use this new feature?
> > To me, that feels like an oversight in the design.
> 
> Trying to enforce “singleton” objects to be able to `===` compare them 
> already requires you to take care of quite a number of things (e.g. 
> making the constructor private, disallowing serialization, …) and 
> cloning is no different in that regard.
> 
> Nevertheless you can make `__clone()` private (which means that cloning 
> is only allowed from within the class, no Exception necessary) and then:
> 
>      private function __clone() { }
> 
>      public function withFoo($foo) {
>          if ($this->foo === $foo) {
>              return $this;
>          }
> 
>          return clone($this, ['foo' => $foo]);
>      }
> 
> To make sure you are only creating a clone when actually changing 
> anything.
> 
> Best regards
> Tim Düsterhus
> 

Thank you, that makes sense.

— Rob

Reply via email to