# [RFC] [DISCUSSION] Compact Object Property Assignment

- Thread: https://staging.externals.io/message/109055
- Original archive: https://news-web.php.net/php.internals/109055
- Started by Jakob Givoni on 2020-03-16T11:48:04+00:00
- Messages: 45
- RFC: Compact Object Property Assignment (Declined) — https://staging.externals.io/rfc/compact-object-property-assignment.md
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://staging.externals.io/message/109055.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://staging.externals.io/search.md?q={query} · RFCs at https://staging.externals.io/rfc.md · JSON API at https://staging.externals.io/api · documentation at https://staging.externals.io/llms.txt

---

## #109055 — Jakob Givoni — 2020-03-16T11:48:04+00:00

URL: https://staging.externals.io/message/109055#109055

Hello Internals,

I'm opening up my new RFC for discussion:

https://wiki.php.net/rfc/compact-object-property-assignment
- A pragmatic approach to object literals

Let me know what you think!

Best,
Jakob

---

## #109058 — Matthew Brown — 2020-03-16T14:10:16+00:00

URL: https://staging.externals.io/message/109055#109058 · In reply to: #109055

I love the idea!

The syntax for new objects looks a little verbose – would it be possible to
use

$foo = new Foo()[
  property1 = "hello",
  property2 = 5,
];

as an alternative to

$foo = (new Foo())->[
  property1 = "hello",
  property2 = 5,
];




> Hello Internals,
>
> I'm opening up my new RFC for discussion:
>
> https://wiki.php.net/rfc/compact-object-property-assignment
> - A pragmatic approach to object literals
>
> Let me know what you think!
>
> Best,
> Jakob

---

## #109059 — Christian Schneider — 2020-03-16T14:26:25+00:00

URL: https://staging.externals.io/message/109055#109059 · In reply to: #109055

Am 16.03.2020 um 12:48 schrieb Jakob Givoni <jakob@givoni.dk>:
> I'm opening up my new RFC for discussion:
> 
> https://wiki.php.net/rfc/compact-object-property-assignment
> - A pragmatic approach to object literals
> 
> Let me know what you think!

Sorry to say but the syntax look very un-PHP-like.

[] suggests an array but then is uses literals and = instead of 'strings'/$vars and => which looks wrong to my PHP eye.

Apart from that it feels weird that you have an object where you want to initialise so many properties manually instead of through some sort of constructor.
Is it more of a record than an object?
I'm not sure if I that is a pattern I would want to encourage.

My $.02,
- Chris

---

## #109060 — Marco Pivetta — 2020-03-16T14:30:54+00:00

URL: https://staging.externals.io/message/109055#109060 · In reply to: #109055

Hey Jakob,

What happens if you have an expression that throws?

class Foo
{
    public $a;
    public $b;
    public $c;
}

$instance = new Foo();

function iThrow() {
    throw new \Exception();
}

try {
    $foo ->[
        a = 'a',
        b = iThrow(),
        c = 'c',
    ];
} catch (\Throwable $e) {
    var_export($foo); // ???
}

What will the state of `$foo` be here?

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/




> Hello Internals,
>
> I'm opening up my new RFC for discussion:
>
> https://wiki.php.net/rfc/compact-object-property-assignment
> - A pragmatic approach to object literals
>
> Let me know what you think!
>
> Best,
> Jakob

---

## #109063 — Rowan Tommins — 2020-03-16T15:40:11+00:00

URL: https://staging.externals.io/message/109055#109063 · In reply to: #109055

> 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]

---

## #109078 — Mike Schinkel — 2020-03-16T18:40:16+00:00

URL: https://staging.externals.io/message/109055#109078 · In reply to: #109058

For reference:

https://wiki.php.net/rfc/object-initializer
https://externals.io/message/106947

That was quite the discussion, and it started only 6 months ago.

-Mike 


> 
> 
> I love the idea!
> 
> The syntax for new objects looks a little verbose – would it be possible to
> use
> 
> $foo = new Foo()[
>  property1 = "hello",
>  property2 = 5,
> ];
> 
> as an alternative to
> 
> $foo = (new Foo())->[
>  property1 = "hello",
>  property2 = 5,
> ];
> 
> 
> 
> 
> > […]

---

## #109083 — Jakob Givoni — 2020-03-17T01:13:27+00:00

URL: https://staging.externals.io/message/109055#109083 · In reply to: #109058

> I love the idea!
Thanks Matthew!

> The syntax for new objects looks a little verbose – would it be possible to use
>
> $foo = new Foo()[
>   property1 = "hello",
>   property2 = 5,
> ];
The short answer: I don't think so.

This is not possible (though it's arguably 'nicer'):

new Foo()->doSomething(); // syntax error, unexpected '->'

Not sure why, but it's necessary to wrap the instantiation in brackets:

(new Foo())->doSomething(); // Ok

If someone can explain why, it would be enlightening!

Furthermore, dropping the arrow would create conflicting syntax with
array access:

$foo[1]; // Array access, give me the element with index 1, can be
used on objects as well
$foo[a = 1]; // Property assignment... ???

I'll update the RFC to reflect your proposal.

Thank you,
Jakob

---

## #109085 — Jakob Givoni — 2020-03-17T01:22:40+00:00

URL: https://staging.externals.io/message/109055#109085 · In reply to: #109059

On Mon, Mar 16, 2020 at 9:26 AM Christian Schneider
<cschneid@cschneid.com> wrote:
> [] suggests an array but then is uses literals and = instead of 'strings'/$vars and => which looks wrong to my PHP eye.
That's ok, square brackets are usually related to arrays and what I
want is something similar to array literals.
The rest of the syntax is exactly the same as when you assign
properties on a object currently.

> you want to initialise so many properties manually instead of through some sort of constructor.
Yes, exactly. From the RFC:
"The purpose of this feature is to lighten the effort of populating
data structures, especially medium to large ones."

And as I say, since we don't have named parameters, this is a
pragmatic alternative.

---

## #109086 — Jakob Givoni — 2020-03-17T01:26:57+00:00

URL: https://staging.externals.io/message/109055#109086 · In reply to: #109060

> What happens if you have an expression that throws?
>
> class Foo
> {
>     public $a;
>     public $b;
>     public $c;
> }
>
> $instance = new Foo();
>
> function iThrow() {
>     throw new \Exception();
> }
>
> try {
>     $foo ->[
>         a = 'a',
>         b = iThrow(),
>         c = 'c',
>     ];
> } catch (\Throwable $e) {
>     var_export($foo); // ???
> }

Hi Marco!
Trivial question - let's see what happens:

Just replace COPA with the old syntax and run it:

try {
    $foo->a = 'a';
    $foo->b = iThrow();
    $foo->x = 'c';
} catch (\Throwable $e) {
    var_export($foo); // ???
}

Result:
Foo::__set_state(array(
   'a' => 'a',
   'b' => NULL,
   'c' => NULL,
))

So the first property will be set, the rest will be left as they were.

Best,
Jakob

---

## #109087 — Marco Pivetta — 2020-03-17T01:29:25+00:00

URL: https://staging.externals.io/message/109055#109087 · In reply to: #109086

Hey Jakob,



> 
> > […]
>
> Hi Marco!
> Trivial question - let's see what happens:
>
> Just replace COPA with the old syntax and run it:
>
> try {
>     $foo->a = 'a';
>     $foo->b = iThrow();
>     $foo->x = 'c';
> } catch (\Throwable $e) {
>     var_export($foo); // ???
> }
>
> Result:
> Foo::__set_state(array(
>    'a' => 'a',
>    'b' => NULL,
>    'c' => NULL,
> ))
>
> So the first property will be set, the rest will be left as they were.
>

That kinda makes the entire feature quite useless/uninteresting to me: if a
this does is desugaring into a set of assignments, then I'm not sure what
its advantage is.

I was kinda hoping for an atomic state mutation across multiple fields,
heh...

---

## #109089 — Jakob Givoni — 2020-03-17T01:47:04+00:00

URL: https://staging.externals.io/message/109055#109089 · In reply to: #109063

> Thanks for having another go at this feature, which I think a lot of people
> would like in some form.
I agree!

> 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.
Remember that the RFC explicitly says it's not an object initializer,
nor does it solve "named parameters" which you mention.
If I had the choice, I'd go with named parameters when creating an
object, but I don't and
this is the next best thing. It's simple and it doesn't introduce any
new concepts.
It just allows you to do something inline that you could until now
only do line by line.

> 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.
The associative array is a common pattern, but it defeats name and
type checking.
An Options class add almost no extra boilerplate since you simply move
the properties from
the main class to the Options class.
Notice that in contrary to your example, I simply copy the Options
object whole into the main class.

> COPA can only validate individual
> parameters, not the whole object; so it's hard to complain if the user
> forgets a mandatory field
Correct, the goals for COPA are quite clear in the "Motivation"
section and that kind of validation
is not one of them
Luckily you can still do things the way you prefer without COPA if it
doesn't suit you :-)

Best,
Jakob

---

## #109090 — Jakob Givoni — 2020-03-17T01:49:31+00:00

URL: https://staging.externals.io/message/109055#109090 · In reply to: #109087

> That kinda makes the entire feature quite useless/uninteresting to me: if a this does is desugaring into a set of assignments, then I'm not sure what its advantage is.
I'm sorry about that, but the motivation of the RFC is quite clear in
the "Motivation" section.
If those goals are not interesting to you then COPA won't help you.

> I was kinda hoping for an atomic state mutation across multiple fields, heh...
Sounds like another RFC (that may make it in PHP 9.x+ ;-D)

---

## #109091 — Jakob Givoni — 2020-03-17T02:07:38+00:00

URL: https://staging.externals.io/message/109055#109091 · In reply to: #109055

> Let me know what you think!

Thank you for your feedback so far!

I'd be really curios to know what authors of the referenced RFCs think
about this, f.ex.
Michał (brzuchal@php.net), Andrey (andrewgrom@rambler.ru) and Nikita
(nikic@php.net)

Is simple inline object population useful in itself?
Is the proposed implementation as trivial as I think it is?

Best regards,
Jakob

---

## #109105 — Rowan Tommins — 2020-03-17T14:30:45+00:00

URL: https://staging.externals.io/message/109055#109105 · In reply to: #109089

> Remember that the RFC explicitly says it's not an object initializer,
> nor does it solve "named parameters" which you mention.
>


I wasn't expecting COPA to "solve" named parameters, just thinking that if
we already had named parameters, we might not bother with COPA.

That said, your "argument bag" example looks very much like it's trying to
solve named parameters to me.




> An Options class add almost no extra boilerplate since you simply move
> the properties from
> the main class to the Options class.
> Notice that in contrary to your example, I simply copy the Options
> object whole into the main class.
>


Hm, I see, that does reduce the boilerplate somewhat, although it's still
split across two classes, and probably therefore two files, which is not
great.

You're missing some code in your example, though, because you've documented
one of the options as optional, implying the others should be mandatory; in
which case you need something like this in the constructor:

         if ( ! isset($options->mane) || ! isset($options->hum) ) {
             throw new Exception('Bad options');
         }

Which would soon get longer with more complex options. Maybe it would be
refactored out into $options->isValid() or something, but it would have to
go somewhere, or you'll just get "uninitialized property" errors in random
parts of your application.

You'd also want to copy the property onto the real object if it was
initialising state rather than retaining a constant value; it would be a
bit weird to write $this->options->counter++ instead of $this->counter++




>
> > […]
> Correct, the goals for COPA are quite clear in the "Motivation"
> section and that kind of validation
> is not one of them
> Luckily you can still do things the way you prefer without COPA if it
> doesn't suit you :-)
>



It's not so much about preferring different styles, it's about what
circumstances this will be useful. It seems pretty rare that an object
would have no mandatory properties, so saying "if you have a mandatory
property, COPA is not for you" is ruling out a lot of uses.

It might be interesting to have the syntax run before the constructor
rather than after, or trigger some other magic method which could do
tidying and validation, so it could apply to more circumstances.


Regards,
-- 
Rowan Tommins
[IMSoP]

---

## #109106 — michal.brzuchalski@gmail.com — 2020-03-17T15:52:06+00:00

URL: https://staging.externals.io/message/109055#109106 · In reply to: #109091

Hi Jakob,

wt., 17 mar 2020 o 03:08 Jakob Givoni <jakob@givoni.dk> napisał(a):

> 
> > […]
>
> Thank you for your feedback so far!
>
> I'd be really curios to know what authors of the referenced RFCs think
> about this, f.ex.
> Michał (brzuchal@php.net), Andrey (andrewgrom@rambler.ru) and Nikita
> (nikic@php.net)
>
> Is simple inline object population useful in itself?
> Is the proposed implementation as trivial as I think it is?
>

For object initializer, I was hoping to introduce a feature which with the
benefits of typed properties
could reduce the boilerplate on initializing object and setting their
properties in one expression.

This is somewhat what I personally do a lot for commands and events
construction where
those simply have public typed properties and I don't care if something
would be changed
in the meantime.

With current RFC for write-once, I can see object initializer could be an
awesome feature
with a combine of read-only properties.

Currently I would have to do a lot of:

$command = new SomeCommand();
$command->foo = 'bar';
$command->baz = true

$this->dispatch($command);

For SomeCommand looking like (with read-only for example purposes)
class SomeCommand {
    public readonly string $foo;
    public readonly bool $baz;
}

With object initializer, this could be reduced to:

$this->dispatch(new SomeCommand { foo = 'bar', baz = false });

But as mentioned IMO this is a different feature than what you propose and
personally I see no point
in reducing only assignment statements without combining it with object
construction for these kinds
of small objects, DTO's, commands, queries and events.

And agree with others that brackets look unnatural for anything related to
objects.

IIRC there were many questions about named parameters to pass for object
constructor or proper
property setters like in C#, but personally I don't need a constructor at
all in those cases since we
have typed properties and it looks like they could be also marked as
read-only in next major PHP version.

Cheers,
--
Michał Brzuchalski

---

## #109115 — Matthew Brown — 2020-03-17T21:33:38+00:00

URL: https://staging.externals.io/message/109055#109115 · In reply to: #109083

I don't think it's conflicting _if you insist on brackets_ after the new
expression. PHP Parser grammar for "new" expressions is

 `T_NEW` class_name_reference ctor_arguments

If you allowed the shorter syntax, ctor_arguments would allow an
object_properties entry.

I'm sure Nikita could clarify, though.




> On Mon, Mar 16, 2020 at 9:10 AM Matthew Brown <matthewmatthew@gmail.com>
> wrote:
> > […]
> Thanks Matthew!
>
> > […]
> to use
> > […]
> The short answer: I don't think so.
>
> This is not possible (though it's arguably 'nicer'):
>
> new Foo()->doSomething(); // syntax error, unexpected '->'
>
> Not sure why, but it's necessary to wrap the instantiation in brackets:
>
> (new Foo())->doSomething(); // Ok
>
> If someone can explain why, it would be enlightening!
>
> Furthermore, dropping the arrow would create conflicting syntax with
> array access:
>
> $foo[1]; // Array access, give me the element with index 1, can be
> used on objects as well
> $foo[a = 1]; // Property assignment... ???
>
> I'll update the RFC to reflect your proposal.
>
> Thank you,
> Jakob

---

## #109118 — Jakob Givoni — 2020-03-18T02:36:21+00:00

URL: https://staging.externals.io/message/109055#109118 · In reply to: #109106

Thank you, Michał, for chiming in :-)

On Tue, Mar 17, 2020 at 10:52 AM Michał Brzuchalski
<michal.brzuchalski@gmail.com> wrote:
> For object initializer, I was hoping to introduce a feature which with the benefits of typed properties
> could reduce the boilerplate on initializing object and setting their properties in one expression.
Exactly my motivation with COPA as well;
- Typed properties - check,
- Reduce boilerplate - check,
- Initializing and setting properties in one expression - check.

> With object initializer, this could be reduced to:
>
> $this->dispatch(new SomeCommand { foo = 'bar', baz = false });
And with COPA it would be;
$this->dispatch((new SomeCommand)->[ foo = 'bar', baz = false ]);
Subtle differences, when compared to the currently available alternative.

> But as mentioned IMO this is a different feature than what you propose and personally I see no point
> in reducing only assignment statements without combining it with object construction for these kinds
> of small objects, DTO's, commands, queries and events.
Maybe you missed that COPA can be combined with object construction?

> but personally I don't need a constructor at all in those cases since we
> have typed properties and it looks like they could be also marked as read-only in next major PHP version.
Exactly, and as I couldn't help notice that you voted for the Write
Once Properties RFC, which clearly states that
object construction is a fuzzy term (meaning don't take it too
seriously) and lazy initialization is a feature...

I hope you will either reconsider your support for COPA or let me know
what I'm missing so I can
consider other directions.

---

## #109119 — Jakob Givoni — 2020-03-18T02:42:20+00:00

URL: https://staging.externals.io/message/109055#109119 · In reply to: #109115

> I don't think it's conflicting _if you insist on brackets_ after the new expression. PHP Parser grammar for "new" expressions is
>
> `T_NEW` class_name_reference ctor_arguments
>
> If you allowed the shorter syntax, ctor_arguments would allow an object_properties entry.
Sounds good, but this is unfamiliar territory to me, so would you mind
giving an example of an
alternative syntax you think would work?

> I'm sure Nikita could clarify, though.
I know Nikita is busy but I hope he'll stop by this RFC one of these
days, as I have a few
things that needs his expertise :-)

---

## #109120 — Jakob Givoni — 2020-03-18T02:57:17+00:00

URL: https://staging.externals.io/message/109055#109120 · In reply to: #109105

> Hm, I see, that does reduce the boilerplate somewhat, although it's still
> split across two classes, and probably therefore two files, which is not
> great.
As an alternative to passive associative arrays, it's a small price to pay for
splitting concerns and having a documented signature for the data structure.
Named parameters is another alternative (unfortunately outside reach for now)
that would work great for a limited number of arguments. COPA does not
make named parameters obsolete, but works great for any number of arguments.

> You're missing some code in your example, though, because you've documented
> one of the options as optional, implying the others should be mandatory; in
> which case you need something like this in the constructor:
I've rewritten parts of the RFC and some examples substantially,
and added your view of mandatory arguments in the "Open Issues" section.

> It might be interesting to have the syntax run before the constructor
> rather than after, or trigger some other magic method which could do
> tidying and validation, so it could apply to more circumstances.
Hmmm, in the Write Once Properties RFC they seem to believe
that object construction is a "fuzzy" term and that lazy initialization
is a feature.

We can add better 'automagic' support for mandatory arguments,
filtering and validation
in incremental proposals, to avoid biting off more than we can chew, but we
have to start somewhere.

---

## #109121 — Jakob Givoni — 2020-03-18T03:02:07+00:00

URL: https://staging.externals.io/message/109055#109121 · In reply to: #109091

> Thank you for your feedback so far!
I've rewritten parts of the RFC substantially
(https://wiki.php.net/rfc/compact-object-property-assignment)
so take another look if you too have ever wanted to
create, populate and send an object inside a function call.

---

## #109122 — michal.brzuchalski@gmail.com — 2020-03-18T05:27:19+00:00

URL: https://staging.externals.io/message/109055#109122 · In reply to: #109118

śr., 18 mar 2020, 03:36 użytkownik Jakob Givoni <jakob@givoni.dk> napisał:

> Thank you, Michał, for chiming in :-)
>
> On Tue, Mar 17, 2020 at 10:52 AM Michał Brzuchalski
> <michal.brzuchalski@gmail.com> wrote:
> > […]
> the benefits of typed properties
> > […]
> properties in one expression.
> Exactly my motivation with COPA as well;
> - Typed properties - check,
> - Reduce boilerplate - check,
> - Initializing and setting properties in one expression - check.
>
> > […]
> And with COPA it would be;
> $this->dispatch((new SomeCommand)->[ foo = 'bar', baz = false ]);
> Subtle differences, when compared to the currently available alternative.
>

The difference is in object state initialization :

Using Object Initializer enforce that if a class is instantiated with the
Object Initializer, at the end of the instantiation and properties
initialization, all visible properties *(depends on initialization scope)* are
initialized, otherwise, a RuntimeException is thrown. This helps to avoid
bugs where a property is added to the class but forgot to be assigned it a
value in all cases where the class is instantiated and initialized.
https://wiki.php.net/rfc/object-initializer#restrictions

You can't do that with COPA cause it has nothing to do with object
instantiation.



> > […]
> and personally I see no point
> > […]
> construction for these kinds
> > […]
> Maybe you missed that COPA can be combined with object construction?
>
> > […]
> read-only in next major PHP version.
> Exactly, and as I couldn't help notice that you voted for the Write
> Once Properties RFC, which clearly states that
> object construction is a fuzzy term (meaning don't take it too
> seriously) and lazy initialization is a feature...
>
> I hope you will either reconsider your support for COPA or let me know
> what I'm missing so I can
> consider other directions.

---

## #109175 — Jakob Givoni — 2020-03-20T23:47:29+00:00

URL: https://staging.externals.io/message/109055#109175 · In reply to: #109122

On Wed, Mar 18, 2020 at 12:27 AM Michał Brzuchalski
<michal.brzuchalski@gmail.com> wrote:

> Using Object Initializer enforce that if a class is instantiated with the Object Initializer,
> at the end of the instantiation and properties initialization, all visible properties
> (depends on initialization scope) are initialized, otherwise, a RuntimeException is thrown.
> This helps to avoid bugs where a property is added to the class but forgot to be assigned
> it a value in all cases where the class is instantiated and initialized. https://wiki.php.net/rfc/object-initializer#restrictions

Got it.
Out of curiosity, would you be able to summarize why you believe your
proposal was not accepted?

---

## #109181 — Andrea Faulds — 2020-03-21T18:31:09+00:00

URL: https://staging.externals.io/message/109055#109181 · In reply to: #109055

Hi,

Jakob Givoni wrote:
> Hello Internals,
> 
> I'm opening up my new RFC for discussion:
> 
> https://wiki.php.net/rfc/compact-object-property-assignment
> - A pragmatic approach to object literals
> 
> Let me know what you think!
> 
> Best,
> Jakob
> 

I really don't like this `(new Foo)->[]` syntax for a few reasons:

* It doesn't seem unreasonable to me to imagine that `->` could be
   overloaded to take a value that isn't a string for the property name.
   Of course, that would be `(new Foo)->{[]}` not `(new Foo)->[]`, but it
   is too close for comfort for me.
* It looks like short array syntax, but it's not an array, in fact
   it is an object, which is a similar but different thing.
* Brackets normally enclose an expression: if I have `new Foo`, I can
   enclose that as `(new Foo)`, yet this is adding something extra to the
   `new` expression while not being part of it? This is surprising to me.
   If it affects the `new`, it should be inside the brackets.
* Do we need the brackets?

I think there are some alternative syntaxes that could be used as 
inspiration.

C99 has a versatile feature called “designated initialisers”, which lets 
you initialise not only structs but arrays:

     // Struct initialisation
     struct some_struct foo = {
         .bar = 1,
         .baz = 2,
     };

     // Array initialisation
     int bar[] = {
         [0] = 1,
         [1] = 2,
     };

Notice how the syntax between the curly braces resemblance the normal 
syntax for accessing and assigning to members of a type. A normal struct 
member assignment on its own looks like `foo.bar = 1;`, so within the 
curly braces you write `.bar = 1,`. Likewise a normal array member 
assignment on its own looks like `bar[0] = 1;`, so within the curly 
braces you write `[0] = 1,`. This resemblance provides familiarity for 
someone seeing the syntax for the first time and provides a clue as to 
what it does, and also retains the visual distinctiveness between array 
and struct assignments.

If we were to copy the C99 model, perhaps it would look something like:

     $foo = new Foo {
         ->bar = 1,
         ->baz = 2,
     };

(I am assuming the call to the constructor has no arguments here, but 
otherwise you would insert the normal argument list brackets before the 
opening `{`. I have used `{` here like C, but perhaps `[` would be 
better. There would also be the question of whether `=` should be `=>` 
if we want to deliberately resemble arrays.)

However, we don't have to be so imaginitive and adapt a similar feature, 
because C# already has the exact feature you are proposing, and calls it 
“object initialisers”:

     Foo foo = new Foo {
         bar = 1,
         baz = 2,
     };

(I am again assuming the call to the constructor has no arguments. If 
there are arguments, they go before the opening `{` in C#.)

I am neutral on whether it's a better or worse syntax than using `->`.

Side-note, C# even supports a special kind of anonymous classes with 
“object initialisers”:

     var foo = new {
         bar = 1,
         baz = 2,
     };

I think PHP won't need this given `new stdClass {` would work perfectly 
well, although it would be nice to have a shorter and prettier 
alternative to the current `(object)[`.

Anyway, thanks for proposing something I have wanted for ages but never 
gotten round to implementing. :)
Andrea

---

## #109182 — Christoph M. Becker — 2020-03-21T18:56:02+00:00

URL: https://staging.externals.io/message/109055#109182 · In reply to: #109181

> However, we don't have to be so imaginitive and adapt a similar feature,
> because C# already has the exact feature you are proposing, and calls it
> “object initialisers”:
>
>     Foo foo = new Foo {
>         bar = 1,
>         baz = 2,
>     };
>
> (I am again assuming the call to the constructor has no arguments. If
> there are arguments, they go before the opening `{` in C#.)
>
> I am neutral on whether it's a better or worse syntax than using `->`.
>
> Side-note, C# even supports a special kind of anonymous classes with
> “object initialisers”:
>
>     var foo = new {
>         bar = 1,
>         baz = 2,
>     };
>
> I think PHP won't need this given `new stdClass {` would work perfectly
> well, although it would be nice to have a shorter and prettier
> alternative to the current `(object)[`.
>
> Anyway, thanks for proposing something I have wanted for ages but never
> gotten round to implementing. :)

This is exactly what the recently declined Object Initializer RFC[1]
proposed. :)

[1] <https://wiki.php.net/rfc/object-initializer>

--
Christoph M. Becker

---

## #109199 — Jakob Givoni — 2020-03-22T02:47:58+00:00

URL: https://staging.externals.io/message/109055#109199

Hi Andrea, thanks for your feedback.
Let's talk about syntax then :-)

The currently suggested syntax is

<object-expression> -> [
    <property-name> = <expression>,
    ...
]

The <object-expression> can be an existing object:

$foo->[a = 1];

Or a new, yet anonymous, object:

(new Foo)->[a = 1];

1. The (normal) brackets
===================

The reason I think it's necessary to wrap the new Foo in brackets is
because it's a language construct and not an expression in itself.
Wrapping it in brackets make it an expression.

For example, these are both syntax errors (missing brackets):
new Foo->a = 1;
new Foo()->setA(1);

In this RFC I did not want to propose changing the lexer/parser to
make that possible, since my focus was to suggest a rather trivial
implementation. I'm open to change this view, but only if someone with
solid knowledge of internals come forward and promise that it's a good
idea.

2. The arrow
==========

When the arrow follows an object expression it suggest we're doing
something on that object, like accessing a property (set/get) or
calling a method.
There are exceptions though: When the object expression is followed by
curly or square brackets it means we're accessing it as if it were an
array:

$foo[1]
$foo{1} // Deprecated

And when it's followed by normal brackets, we're invoking it as a callable:

$foo()

I see a window of opportunity here though: Since the curly brackets
were deprecated in PHP 7.4 we could repurpose it for COPA:

$foo{a = 1, b = 2}

Is it too soon?

3. The square brackets
==================

The assignments need to be grouped together, somehow (at least I think
that's the sane thing to do?) - we cannot use curly brackets as, like
you say, that's reserved to create an expression that evaluates to a
property name:

$foo->{a =1, b = 2}; // syntax error, unexpected '='

That leaves us with either normal brackets or square brackets:

$foo->(a = 1, b = 2);
$foo->[a = 1, b = 2];

Which one is more natural when we're dealing with structure data?

4. The property name
================

All I can say is that I really don't want to add anything that is not
strictly necessary, like the arrow before each property, unless it's
adding something of actual value.
Familiarity you say... yes, I can see that, but it gets very verbose
with that leading arrow... In my opinion array literal syntax is
already too verbose for me.

5. The equals sign
==============

I don't really know why => was chosen for array assignment, since we
use simple = to assign values everywhere else. Since i prefer it less
verbose, and since we already
use = in $foo->a = 1 I think a single = is the best option.

COPA is NOT object initializer
=======================

COPA can follow any object expression and has nothing to do with
object construction in itself. You can use COPA as many times as you
like at any point in an object's life.
Though object initializer would also solve what COPA is solving, COPA
doesn't introduce any new concepts, just new syntax.
I don't know why object initializer and other similar proposals failed
in the past, but I wanted to try something different, less elaborate
and more pragmatic.
I don't know if COPA has any better chance than those that came before :-)

I am going to suggest a few alternative syntaxes that we can also vote
on, but only after they've been vetted by experienced internals
developers.

Syntax A - the initial one

Syntax B:
$foo{
  a = 1,
  b = 2,
};

Syntax C:
$foo->a = 1,
  b = 2;

Syntax D:
$foo->a = 1,
       ->b = 2;

Syntax E:
$foo->(
  a = 1,
  b = 2,
);

We can try to iterate over these as well, please let me know what you think!


>
> Hi,
>
> Jakob Givoni wrote:
> > […]
>
> I really don't like this `(new Foo)->[]` syntax for a few reasons:
>
> * It doesn't seem unreasonable to me to imagine that `->` could be
>    overloaded to take a value that isn't a string for the property name.
>    Of course, that would be `(new Foo)->{[]}` not `(new Foo)->[]`, but it
>    is too close for comfort for me.
> * It looks like short array syntax, but it's not an array, in fact
>    it is an object, which is a similar but different thing.
> * Brackets normally enclose an expression: if I have `new Foo`, I can
>    enclose that as `(new Foo)`, yet this is adding something extra to the
>    `new` expression while not being part of it? This is surprising to me.
>    If it affects the `new`, it should be inside the brackets.
> * Do we need the brackets?
>
> I think there are some alternative syntaxes that could be used as
> inspiration.
>
> C99 has a versatile feature called “designated initialisers”, which lets
> you initialise not only structs but arrays:
>
>      // Struct initialisation
>      struct some_struct foo = {
>          .bar = 1,
>          .baz = 2,
>      };
>
>      // Array initialisation
>      int bar[] = {
>          [0] = 1,
>          [1] = 2,
>      };
>
> Notice how the syntax between the curly braces resemblance the normal
> syntax for accessing and assigning to members of a type. A normal struct
> member assignment on its own looks like `foo.bar = 1;`, so within the
> curly braces you write `.bar = 1,`. Likewise a normal array member
> assignment on its own looks like `bar[0] = 1;`, so within the curly
> braces you write `[0] = 1,`. This resemblance provides familiarity for
> someone seeing the syntax for the first time and provides a clue as to
> what it does, and also retains the visual distinctiveness between array
> and struct assignments.
>
> If we were to copy the C99 model, perhaps it would look something like:
>
>      $foo = new Foo {
>          ->bar = 1,
>          ->baz = 2,
>      };
>
> (I am assuming the call to the constructor has no arguments here, but
> otherwise you would insert the normal argument list brackets before the
> opening `{`. I have used `{` here like C, but perhaps `[` would be
> better. There would also be the question of whether `=` should be `=>`
> if we want to deliberately resemble arrays.)
>
> However, we don't have to be so imaginitive and adapt a similar feature,
> because C# already has the exact feature you are proposing, and calls it
> “object initialisers”:
>
>      Foo foo = new Foo {
>          bar = 1,
>          baz = 2,
>      };
>
> (I am again assuming the call to the constructor has no arguments. If
> there are arguments, they go before the opening `{` in C#.)
>
> I am neutral on whether it's a better or worse syntax than using `->`.
>
> Side-note, C# even supports a special kind of anonymous classes with
> “object initialisers”:
>
>      var foo = new {
>          bar = 1,
>          baz = 2,
>      };
>
> I think PHP won't need this given `new stdClass {` would work perfectly
> well, although it would be nice to have a shorter and prettier
> alternative to the current `(object)[`.
>
> Anyway, thanks for proposing something I have wanted for ages but never
> gotten round to implementing. :)
> Andrea

---

Next page: https://staging.externals.io/message/109055.md?page=2
