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']
5
  • 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. Nov 14, 2022 at 18:33
  • Related: stackoverflow.com/questions/17455043/…
    – Blackhole
    Nov 14, 2022 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, 2022 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, 2022 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. Nov 15, 2022 at 9:47

1 Answer 1

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);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.