On 21/06/2021 17:54, tyson andre wrote:
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]`.
This is an immediate "no" from me: it multiplies the ways to write the
same thing from 2 to 4, in order to save a few bytes, in a few instances.
I think this is something that Douglas Crockford got absolutely right
when he simplified JavaScript object syntax to formalise JSON: every
valid key can be represented as a quoted string, so if the quotes are
always there, you don't need to remember a list of rules about reserved
words, allowed characters, etc.
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];
```
Although common, this is not a good use of arrays; if your keys are
"known literals", they should be fields of some object:
return new Result(success: true, data: $data, cursor: $cursor);
If you don't want to declare a class (yet), you can use an anonymous
object. Rather than yet another way to write arrays, it would be great
to have some more powerful syntax for those; currently you'd have
something like this:
return new class(success: true, data: $data, cursor: $cursor) { public
function __construct(public bool $success, public array $data, public
CursorInterface $cursor) {} };
Brainstorming, we could perhaps extend property promotion into the "new
class" clause, so that you could write this:
return new class(public bool success: true, public array data: $data,
public CursorInterface cursor: $cursor) {};
Regards,
--
Rowan Tommins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php