Shorthand proposal for associative arrays
| From: | Christian Schneider | Date: | Fri, 26 Jan 2018 18:16:26 +0000 |
| Subject: | Shorthand proposal for associative arrays | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-101698@lists.php.net to get a copy of this message | ||
Hi there,
I have a proposal for a shorthand notation of associative arrays borrowed from another language:
:$foo
would be equivalent to
'foo' => $foo
and would work with array, list or []
Motivation behind it, maybe someone else finds more good uses:
1) Emulating named parameters with associative arrays like
html::img([ 'src' => $src, 'alt' => $alt ]);
could be written as
html::img([ :$src, :$alt ]);
which encourages consistent naming of variables and parameters
2) Simplifying list destructuring with non-integer keys, example taking from http://php.net/manual/en/migration71.new-features.php#migration71.new-features.support-for-keys-in-list
foreach ($data as ["id" => $id, "name" => $name]) {
becomes
foreach ($data as [ :$id, :$name ]) {
which reduces redundancy.
I implemented a minimal patch (2 lines are added to the parser) to implement this which you can find
at
https://cschneid.com/php/php7_2/assoc_array_shorthand.patch
What do you think, is this worth an RFC? I hope I didn't miss an existing one :-)
Regards,
- Chris