Re: [RFC] Object Initializer

From: Date: Fri, 13 Sep 2019 06:39:52 +0000
Subject: Re: [RFC] Object Initializer
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-107043@lists.php.net to get a copy of this message
> Le 13 sept. 2019 à 07:49, Michał Brzuchalski <michal.brzuchalski@gmail.com> a écrit : > > Hi Lynn, > > czw., 12 wrz 2019 o 17:01 Lynn <kjarli@gmail.com > <mailto: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

« previous php.internals (#107043) next »