On Tue, June 27, 2023, 6:33 Rowan Tommins wrote:
> On 27/06/2023 02:25, Theodore Brown wrote:
> > Currently the following code returns only the array keys that loosely equal 
> > null:
> >
> >      array_keys($array, null)
> >
> > If the function is changed to a single signature with $filter_value 
> > defaulting to null (with an argument count check to preserve the above 
> > functionality), its behavior becomes a lot more surprising/unexpected. If a 
> > parameter defaults to null, as a user I don't expect the function to work 
> > differently when I explicitly pass the default value.
> 
> 
> An alternative solution to this situation is to introduce a new dummy
> value for such parameters, similar to how JavaScript uses the special
> "Symbol" type to have keys that can't collide with any userland value.
> In this context, this could be achieved with a single-value enum, i.e.:
> 
> enum ArrayKeys { case IncludeAll; }
> 
> function array_keys(array $array, mixed $filter_value =
> ArrayKeys::IncludeAll, bool $strict = false): array {}
> 
> That way, the optional parameter has a real default value, distinct from
> any value the user might wish to filter by, including null, and full
> compatibility is maintained with existing code.
> 
> I don't know whether this is a direction we want to go, but thought I'd
> throw it out there.


That's an interesting idea, but I'm not sure it would make the behavior any 
less confusing. Are single-value enums used like this anywhere else in PHP? As 
a user my expectation when seeing `ArrayKeys::IncludeAll` as the default is 
that there must be other `ArrayKeys` enum values for additional options.

Note that currently there is a draft RFC to support objects in array keys. [1] 
If that feature is accepted, would it not be allowed to filter array keys by 
the `ArrayKeys::IncludeAll` enum value? That would also be 
surprising/unexpected.

Based on the current vote tally, `array_keys` looks like it will be the only 
remaining function in PHP 9 with an overloaded signature, which would make it 
all the more strange.

[1]: https://wiki.php.net/rfc/object_keys_in_arrays
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to