Re: [RFC] Allow object keys in arrays
| From: | Nikita Popov | Date: | Mon, 18 Jan 2021 14:33:55 +0000 |
| Subject: | Re: [RFC] Allow object keys in arrays | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-112920@lists.php.net to get a copy of this message | ||
On Wed, Jan 13, 2021 at 10:08 AM Rowan Tommins <rowan.collins@gmail.com>
wrote:
> On 12/01/2021 16:51, Marco Pivetta wrote:
> > Whether the problem can be mitigated is what should be discussed, but the
> > problem is objectively there.
>
>
> Hi all,
>
> Like others, I like the *idea* of object keys, but worry about its
> practical impact.
>
> A few scatter-gun thoughts on possible approaches, I don't think any of
> them is the solution, but maybe they'll spark someone else to further
> ideas:
>
>
> - Only allow objects that are "stringable" (i.e. implement __toString),
> but don't actually call it. This retains the safety of code using
> "(string)$key", but not code passing to a constraint of "string|int".
> (It also means enums will all have to have an __toString, which might be
> a price worth paying.)
>
> - Create a new type, which is like an array but allows object keys, with
> its own literal syntax. e.g.
>
> $hash = hash['foo' => 42, $someObject => 69];
> assert(is_array($hash) === false);
> assert(is_iterable($hash) === true);
>
> - Invent a syntax for initialising a custom collection object from a
> literal with arbitrary keys and values, but not actually initialise it
> as an array. Even without generics, this would make it much more
> attractive to replace more arrays with specific collection types.
>
I don't think a separate dictionary type would really help (in the context
of this discussion). If you're working with arrays, you already either
treat it as a vector (in which case the keys are irrelevant) or as a
dictionary (in which case you would need to deal with object keys
regardless of whether you call it "array" or "dict"). I think a dedicated
dictionary type can have other benefits (primarily removing numeric string
-> int canonicalization), but I don't think that distinguishing allowed key
types based on it is a good idea. (If we introduced such a type, I would
expect it to have the same key requirements as normal arrays, because both
types would have to be strongly interoperable, and allow mostly seamless
conversions.)
Regards,
Nikita