Re: [PHP-DEV] [RFC] Object Initializer

This is only part of a thread. view whole thread
  107045
September 13, 2019 07:15 michal.brzuchalski@gmail.com (=?UTF-8?Q?Micha=C5=82_Brzuchalski?=)
Hi Claude,

pt., 13 wrz 2019 o 08:39 Claude Pache pache@gmail.com> napisał(a):

> > > Le 13 sept. 2019 à 07:49, Michał Brzuchalski brzuchalski@gmail.com> > a écrit : > > Hi Lynn, > > czw., 12 wrz 2019 o 17:01 Lynn <kjarli@gmail.com> napisał(a): > > Heya, > > What's the added benefit of this compared to implementing a constructor? > > 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}; > } > ``` > > > Removing stdClass for instantiation and initialization of simple objects is > one of a future scope proposal. > > This RFC tries to address instantiation and initialization boilerplate > reduction with a syntax which would > not be restricted to stdClass only. > > Although it's not a game-changer, simple addition to the language which > reduces boilerplate when dealing > with objects which don't need complex constructors like for eg. DTO > objects. > > > As for `stdClass`, PHP has already a syntax: > > $baz = "baz"; > $obj = (object) [ > "foo" => "bar", > $baz => true > ]; > > For other type of objects, that could be done with a simple helper function > > $customer = object_assign(new Customer, [ > "id" => 123, > "name" => "John Doe", > ]); > > where: > > function object_assign(object $obj, iterable $data): object { > foreach ($data as $key => $value) { > $obj->$key = $value; > } > return $obj; > } > > That said, I generally use arrays rather than DTO objects or such, so that > I can’t speak from experience. > > —Claude > > You're of course right this can be done more or less with a helper function
which does all the required type validation through reflection, but I believe that feature requests for language support which reduces boilerplate can easily spread that simplification and bring all the required type check validations out of the box, right? IMO the thing is as you said this would require a helper function and not all simply like them! Regards, Michał Brzuchalski