>
> $person = new Person("Name", 43) {
>
      firstName: "John",
>
      age: 42
>
   };



Hi!

You could achieve similar functionality with a simple user-land method
"assign". If you put such a method on a trait, you can use it everywhere.

See the example:

<?php

trait AssignsPropertiesValues
{
    public function assign(...$props): static
    {
        foreach ($props as $propName => $propVal) {
            $this->$propName = $propVal;
        }

        return $this;
    }
}

class Person
{
    use AssignsPropertiesValues;

    public function __construct(
        public string $firstName,
        public int $age
    ) {
    }
}

class Person2
{
    use AssignsPropertiesValues;

    public string $firstName;
    public int $age;
}

class Person3
{
    use AssignsPropertiesValues;

    public string $firstName { set => \strtoupper($value); }
    public int $age;
}

$p1 = new Person('Pig',5)->assign(firstName: 'Peppa', age: 6);
$p2 = new Person2()->assign(firstName: 'George', age: 3);
$p3 = new Person3()->assign(firstName: 'Danny', age: 7);

var_dump($p1, $p2, $p3);

https://3v4l.org/F83NO#v8.4.1

Best regards,
Erick

Reply via email to