> What's the added benefit of this compared to implementing a constructor?
Michal my have a different answer but my answer are the following two benefits
plus a 3rd related benefit:
1. The ability to add strictness to object initialization vs. using arrays of
properties. PHP itself could flag misspelled or missing properties with a
warning or an error which is something PHP cannot really do given that array
keys are strings and not identifiers.
2. The ability for tools like PhpStorm, PHStan and others to more easily
identify and flag these errors. It is hard (impossible?) for a tool to validate
array element keys because there is no way to declare named and typed array
elements keys in PHP.
3. It would empowering developers to pass optional elements to functions and
methods that can also be type checked. The 2nd example would allow type
checking but the first would not:
EXAMPLE 1
function foo( int $id, array $args ) {
...
}
foo( 1, array(
"bar" => "abc",
"baz" => 123,
}
EXAMPLE 2
class FooArgs {
public string $bar
public int $baz
}
function foo( int $id, FooArgs $args ) {
...
}
foo( 1, FooArgs{
bar = "abc",
baz = 123,
}
-Mike
> The part I like is that this can be used to replace stdClass/structured
> arrays. Perhaps something like this would nice to have in PHP:
>
> ```
> $people = [];
>
> foreach ($peopleFromDatabase as [$id, $username, $name]) {
> $people[] = {
> Uuid id => $id,
> string username => $username,
> string name => $name,
> };
> // and possible automatic assignment:
> $people[] = {Uuid $id, string $username, string $name};
> }
> ```
>
> Regards,
> Lynn van der Berg