[php-src] PR #19329: Add `func_get_named_args()`
| From: | alexandre-daubois | Date: | Thu, 31 Jul 2025 11:12:28 +0000 |
| Subject: | [php-src] PR #19329: Add `func_get_named_args()` | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-32728@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/19329
Author: alexandre-daubois
I'm not entirely sure this would require a RFC. That's why I'm proposing this PR
first, and I'll gladly write an RFC if someone requires it.
Allows to write the following code:
```php
<?php
function hello(string $name, int $age, ...$args): array {
return func_get_named_args();
}
var_dump(hello('World', 30, 'extra1', 'extra2'));
```
Output:
```
array(4) {
["name"]=>
string(5) "World"
["age"]=>
int(30)
[2]=>
string(6) "extra1"
[3]=>
string(6) "extra2"
}
```
I think this would be a nice addition. With named arguments being more and more popular and the
possibility to leverage arrays spreading operator, adding this function feels natural. There's
no easy way to do so currently without using reflection.
They differ a bit on they behavior with spread operator and variadic argument:
```php
function hello(string $name, int $age, ...$args): array {
return func_get_args();
}
var_dump(hello(...[
'age' => 30,
'name' => 'John',
'extra' => 'data',
]));
/*
array(2) {
[0]=>
string(4) "John"
[1]=>
int(30)
}
-> 'extra' is missing in this output
*/
function hello_named(string $name, int $age, ...$args): array {
return func_get_named_args();
}
var_dump(hello_named(...[
'age' => 30,
'name' => 'John',
'extra' => 'data',
]));
/*
array(3) {
["name"]=>
string(4) "John"
["age"]=>
int(30)
["extra"]=>
string(4) "data"
}
*/
```
Adding this function instead of updating
func_get_args() seems better to me, which
avoids any breaking change.