On Mon, 16 Mar 2020 at 11:48, Jakob Givoni <ja...@givoni.dk> wrote: > https://wiki.php.net/rfc/compact-object-property-assignment > - A pragmatic approach to object literals > > Let me know what you think! >
Hi Jakob, Thanks for having another go at this feature, which I think a lot of people would like in some form. I think I agree with Matthew that the almost-but-not-quite array syntax looks a bit odd, but that's something that can be worked on if we agree the basic idea is sound. I fear that the need to directly set public properties (or use __set) would limit the use cases of this somewhat. I can see two ways we could arrive at something more broadly useful: * A syntax like this, plus better support for property setters (inline like in C# etc, rather than needing __set) * Named parameters plus short-hand constructor definitions (e.g. function __construct($this->foo) removing the need to type $this->foo = $foo) Maybe we want to have all four, but that would leave us with a lot of different ways of initialising objects, which might not be such a good thing. You mention using "argument bag" objects in place of named parameters, but that feels like it would be even more awkward than using an associative array. To get the example in the RFC doing something useful, you'd need quite a lot of boilerplate: class FooOptions { string $mane; string $hum; } class Foo { string $mane; string $hum; public function __construct(FooOptions $options) { // Still have to check for uninitialized properties, since COPA won't enforce them if ( ! isset($options->mane) || ! isset($options->hum) ) { throw new Exception('Bad options'); } // Still have to copy parameters one at a time $this->mane = $options->mane; $this-> hum = $options->hum; } } $myFoo = new Foo((new FooOptions())->[ mane = 'get', hum = 'life', ]); Compare that to named parameters (picking a syntax that looks similar to yours), even without any new constructor syntax: class Foo { string $mane; string $hum; public function __construct(string $mane, string $hum) { // Type and mandatory param checks are automatic // Still have to copy parameters one at a time, unless we $this->mane = $mane; $this-> hum = $hum; } } $myFoo = new Foo([ mane = 'get', hum = 'life', ]); Writing that out also made me realise a key difference between this and constructor short-hands, which is that COPA can only validate individual parameters, not the whole object; so it's hard to complain if the user forgets a mandatory field. Sometimes that wouldn't matter, but again, it limits the cases where this syntax would be useful, even if we had property setters. Regards, -- Rowan Tommins [IMSoP]