Re: [PROPOSAL] Bare name array literals (again)

From: Date: Mon, 21 Jun 2021 17:34:11 +0000
Subject: Re: [PROPOSAL] Bare name array literals (again)
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-114983@lists.php.net to get a copy of this message
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.
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]

Thread (12 messages)

« previous php.internals (#114983) next »