On Tue, Apr 2, 2024 at 9:18 AM Ilija Tovilo <tovilo.il...@gmail.com> wrote:
>
> Hi everyone!
>
> I'd like to introduce an idea I've played around with for a couple of
> weeks: Data classes, sometimes called structs in other languages (e.g.
> Swift and C#).
>
> ```php
> data class Vector {
>     private $values;
>
>     public function __construct(...$values) {
>         $this->values = $values;
>     }
>
>     public mutating function append($value) {
>         $this->values[] = $value;
>     }
> }
>
> $a = new Vector(1, 2, 3);
> $b = $a;
> $b->append!(4);
> var_dump($a); // Vector(1, 2, 3)
> var_dump($b); // Vector(1, 2, 3, 4)
> ```
>


While I like the idea, I would like to suggest something else in
addition or as a separate feature. As an active user of readonly
classes with all promoted properties for data-holding purposes, I
would be happy to see the possibility of cloning them with passing
some properties to modify:

readonly class Data {
    function __construct(
        public string $foo,
        public string $bar,
        public string $baz,
) {}
}

$data = new Data(foo: 'A', bar: 'B', baz: 'C');

$data2 = clone $data with (bar: 'X', baz: 'Y');

Under the hood, this "clone" will copy all values of promoted
properties as is but modify some of them to custom values specified by
the user. The implementation of this functionality in the userland
destroys the beauty of readonly classes with promoted properties.
Manual implementation requires a lot of code lines while bringing no
sense to users who read this code. Cloning methods are bigger than the
meaningful part of the class - the constructor with properties
declaration. Because I have to redeclare all the properties in the
method arguments and then initialize each property with a
corresponding value. I love readonly classes with promoted properties
for data-holding purposes and the above feature is the only one I'm
missing to be completely happy.

In my personal experience, I never needed to copy data classes like
arrays, the immutability protects against unwanted changes enough. But
copying references helps to save memory, some datasets I work with can
be very big.

--
Best,
Alex

Reply via email to