Re: Associated Arrays as function parameters
| From: | Mike Schinkel | Date: | Sat, 14 Mar 2020 15:57:05 +0000 |
| Subject: | Re: Associated Arrays as function parameters | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-109017@lists.php.net to get a copy of this message | ||
> On Mar 14, 2020, at 11:07 AM, G. P. B. <george.banyard@gmail.com> wrote:
>
> On Sat, 14 Mar 2020 at 15:43, Midori Koçak <mtkocak@gmail.com> wrote:
>
>> Dear Internals,
>>
>> I would like to as you a question. I know that it is possible to use an
>> array to function parameters like: function(...array); But this method is
>> not working when the array is associative.
>>
>> Would not be fine if an array like ['param1'=>'value',
>> 'param2' => 'value']
>> would be used in a function like function(param1, param2) regardless of the
>> order?
>>
>> I think it would make our lives is easier. I'd be also happy if you know if
>> there is more effective method to achieve the same result.
>>
>> Thanks,
>> Midori
>>
>
> What you are looking for are Named Parameters, there have been multiple
> RFCs about which have all been more or less abandoned from what I see.
> https://wiki.php.net/rfc/namedparameters (From 2012)
> https://wiki.php.net/rfc/named_params (From 2013)
> https://wiki.php.net/rfc/simplified_named_params (From 2016)
Can anyone summarize why these did not move forward?
Nikita's proposal sounds pretty good IMO, and I think the follow up proposal would have been
nice, too. Any port in a storm!
> On a side note, I don't think this feature is *that* useful and if you get
> to the point where you want to know which value you are passing to
> which argument it seems, to me, that the function is having too many
> arguments. Also IDEs exist and can tell you the name of the argument.
I would assert a counter to your assertion that this feature would not be *that* useful, at least
several known use-cases.
The known use-cases include:
1. Querying, be it SQL or some other query language.
2. Wrapping API calls (which is a form of querying.)
3. Instantiating properties of an object via __construct().
I assume most on this list are not fans of WordPress but that notwithstanding WP_Query() is a good
example of a class that accepts an array of arguments on instantiation:
- https://developer.wordpress.org/reference/classes/wp_query/
Unfortunately PHP can't type check those WP_Query() arguments, but it could type check named
parameters of a query() method.
Yes, you can model all arguments as properties of an object, but then how would you instantiate that
class? Named properties would make doing so much less tedious and allow it to be done in a single
expression rather than requiring multiple assignment statements.
-Mike
P.S. This would be on my top 5 list of features I would like to see added in PHP 8. FWIW.