[PROPOSAL] Bare name array literals (again)

From: Date: Mon, 21 Jun 2021 16:54:26 +0000
Subject: [PROPOSAL] Bare name array literals (again)
Groups: php.internals 
Request: Send a blank email to internals+get-114981@lists.php.net to get a copy of this message
Hi internals,

In every place where key is a valid php identifier
(e.g. can be used in PHP 8.0's named parameters),
I propose to allow [key: expr] to be used instead of ['key' =>
expr].
(including list(key: expr) and array(key: expr)
(This can be mixed anywhere with existing key/value syntax such as $key => $value,
..., etc)

The implementation can be found inathttps://github.com/php/php-src/pull/6635

This is useful for shortening long arrays where the keys are known literals,
e.g.

```php
return [success: true, data: $data, cursor: $cursor];
// is equivalent to the following, but shorter:
return ['success' => true, 'data' => $data, 'cursor' =>
$cursor];
```

This uses a similar syntax to named parameter invocations,
making it unlikely to cause future parser conflicts.

```php
// Invoking a function with PHP 8.0 named parameters.
process_api_result(success: true, data: $data);
```

This can also be used in the older array() value and list() destructuring
syntaxes. Forbidding key: value there seemed like
an unnecessary restriction that would make
the language harder to remember and a language specification a bit longer.

I haven't written up an RFC yet, but an older RFC for PHP 5 https://wiki.php.net/rfc/bare_name_array_literal
includes most of the arguments I plan to make, as well as the PR description. Things that have
changed since then include:

- In php 8.0, named parameters were already added, so the key: expr syntax is not
likely to cause conflicts with future syntax.
- Users would already be familiar with this syntax and its meaning due to named parameters.
- There are better open source static analyzers to detect misuse of array keys or passing unexpected
types to arrays (Phan, Psalm, PHPStan) when code is properly annotated

https://wiki.php.net/rfc/named_params#shorthand_syntax_for_matching_parameter_and_variable_name
mentioned this among the future scope.
It had also suggested :$var or =$var as shorthand for var:
$var, but this is going to be left out of this feedback - https://externals.io/message/101698 has mostly
negative feedback on a recent proposal (and there are multiple syntax candidates)

Any feedback?

Thanks,
Tyson


Thread (12 messages)

« previous php.internals (#114981) next »