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

September 13, 2019 10:15 arnold.adaniels.nl@gmail.com (Arnold Daniels)
> I don't like how it works for anonymous classes. It's more difficult to >> implement since the compiler doesn't know the meaning of the (first) >> bracket. It's doesn't make the code more readable, for the same reason. I >> think it's better to not support this syntax with anonymous classes. >> >> > Probably lexical scope for anon classes would be better here, but due to > fact that proposal is to > use initializer block instead of constructor arguments, that was the > reason why initializer block > got before anon class definitions. >
This adds a lot of complexity to the implementation for very little benefit, as the code (as presented for anonymous classes) is really confusing.
> >> The examples do not show how constructor arguments are passed. I'm >> assuming >> it's >> >> $customer = new Customer("foo") { >> name = "John" >> }; >> >> > The examples don't show that cause it's forbidden. > There is a note on that in RFC on purpose > > > Note! Object instantiation allows only constructors without required > arguments to be used. > > Any class which requires passing arguments to constructor cannot be used > in combination with object initializer. > > Using constructor arguments and object initializer would introduce noise > and you'll be potentially initializing object twice: > using object initializer block and using constructor args what may be > misleading. >
I don't see any technical limitation to justify this. $user = new User($organization) { name = "John Doe", email = "john@example.com", }; Is just equivalent to $user = new User($organization); $user->name = "John Doe"; $user->email = "john@example.com";
> Setting the properties does not interfere with the constructor. This is also confirmed by
> constructors are called before initialization takes apart
You may use constructor argument `$organization` to setup the object. The initiate syntax isn't a replacement for the constructor, it's a replacement for setting properties after the object has been constructed.
> Ok, I will let Arnold reply to you on this if he feels that your reply did > not address his concerns. > > Omitting stdClass is outside the scope of the current RFC. I'm inclined not
to discuss it further or take it into consideration for this RFC. New RFC, new discussion. However, I do agree with Mike that using `=>` is more intuitive. It's not specific to array key pairs, because you only use that syntax at initialization of the array. $user = [ 'name' => "John Doe", 'email' => "john@example.com", ]; and $user = []; $user['name'] = "John Doe"; $user['email'] = "john@example.com"; The following feels similar $user = new User { name => "John Doe", email => "john@example.com", }; and $user = new User; $user->name = "John Doe"; $user->email = "john@example.com";