Re: [RFC] Allow object keys in arrays
| From: | Larry Garfield | Date: | Tue, 12 Jan 2021 18:41:33 +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-112857@lists.php.net to get a copy of this message | ||
On Tue, Jan 12, 2021, at 11:53 AM, Andreas Leathley wrote:
> On 12.01.21 17:51, Marco Pivetta wrote:
> > Code written to deal with
array in a generic way will no
> > longer work
> > when
> > invoked through code paths that produce object keys: this is a general
> > problem with widening types overall, and is a clear BC break.
>
> If you look at levels of BC break, this is on the very low end in my
> opinion. No existing code will break when upgrading to this new PHP
> version. Only new code written specifically for that PHP version would
> be impacted, and frameworks/libraries could, if necessary, add
> additional checks without becoming incompatible with older PHP versions.
> It helps that currently array keys can be integers or strings, so if the
> key type is important, some checking is already necessary.
This is untrue. It's quite possible to have code like this today:
function make_list(array $vals) {
$out = '<select>';
foreach ($vals as $key => $label) {
$out .= sprintf('<option value="%s">%s</option>', $key, $label);
}
return $out . '</select>';
}
That would work just fine today with string or int keys, but would break if on an object-keyed array
if the objects did not implement __toString().
Whether the risk of such code breaking in practice is large or small is another question, and I
don't have an answer for it. I'm of mixed feelings on this RFC; on the one hand, it would
make Enums even easier to work with, which is good. On the other, it pours even more behavior into
the kitchen sink data structure whose (mis)use is a known security hole, which is bad. I'd
like to see us using naked hash tables less, not more.
Ilija is also correct that minor potential-breaks like this have been introduced in the past, and
the world has not ended. Whether that is good or bad, historically, is debatable and likely varies
with the specific feature.
I would say that if this RFC moves forward, we would also want to introduce an other array_is_*()
function to make adding extra guards easier. I'm not sure what we'd call it, though.
array_is_keyed? array_is_assoc? array_is_not_objects? Bikeshed as you wish. :-) But we'd
want some easy way to tell what key-style an array uses.
... maybe a function that returns an internal enumeration of List, Assoc, or Object for the 3 key
types? :-)
--Larry Garfield