- Output for 8.4.1
- object(Person)#1 (2) { ["firstName"]=> string(5) "Peppa" ["age"]=> int(6) } object(Person2)#2 (2) { ["firstName"]=> string(6) "George" ["age"]=> int(3) } object(Person3)#3 (2) { ["firstName"]=> string(5) "DANNY" ["age"]=> int(7) }
<?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);