On Mon, Jun 21, 2021, at 12:34 PM, Rowan Tommins wrote:
> 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) {};

I agree with Rowan on both points.  The issues this would supposedly solve a 
better solved by continuing to work on making real-objects easier to work with. 
 PHP 8 made huge strides in that area.  Making anon classes easier would be the 
next logical step.

Also, Mel mentioned destructuring.  Ilija has partially-finished work on a 
pattern matching operator that would include destructuring here:

https://wiki.php.net/rfc/pattern-matching

It's not going to make it into 8.1, sadly, but hopefully that or something like 
it would make it into 8.2.

--Larry Garfield

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to