2

func_get_args() return the arguments passed to a function. Since named parameters are supported in PHP8, is there a way to get the arguments as a hash instead of an array?

That is

function x(string $firstName, string $middleInitial) {
    return func_get_args(); 
}
x('John', 'J'); // returns ['John','J']
x(middleInitial: 'J', firstName: 'John'); // returns ['John','J']

// is there a way to get ['firstName' => 'John, 'middleInitial' => 'J']
Tac Tacelosky
  • 3,165
  • 3
  • 27
  • 28
  • You could use `return ['firstName' => $firstName, 'middleInitial' => $middleInitial]'`. It will do what you want, but I think that's not what your question is about. – KIKO Software Nov 14 '22 at 18:33
  • Related: https://stackoverflow.com/questions/17455043/how-to-get-functions-parameters-names-in-php – Blackhole Nov 14 '22 at 18:33
  • Can you clarify if: 1) you want the parameter names just inside the function, or outside as well; 2) you want to distinguish named argument call from standard call. P.S. : daily reminder that PHP implementing named arguments is a gross mistake. – Blackhole Nov 14 '22 at 18:38
  • @Blackhole - not sure if *P.S. : daily reminder that PHP implementing named arguments is a gross mistake.* is generally accepted. – Nigel Ren Nov 14 '22 at 18:55
  • 1
    Named arguments can potentially lead to readable code like `json_decode($json, associative: true)`, which is definitively bad for job security. – Álvaro González Nov 15 '22 at 09:47

1 Answers1

2

You can use get_defined_vars() method at the beginning of the function:

function x($a, $b) {
    $passed = get_defined_vars();
    var_dump($passed);
}
Amir MB
  • 3,233
  • 2
  • 10
  • 16