3

I have a php function function foo($bar1, $bar2, $bar3)

Is there a possibility to get the parameter names and values dynamically?

I found func_get_args (http://php.net/manual/de/function.func-get-args.php) but that will return something like

0 => "valueOf$bar1", 1=> "valueOf$bar2", 2 => "valueOf$bar3"

What I want instead is something like:

"$bar1" => "valueOf$bar1", "$bar2"=> "valueOf$bar2", "$bar3" => "valueOf$bar3"

Is that possible?

2
  • 2
    Short answer: no. If you want to pass key/value pairs, use an array or an object. Long(er) answer: Yes it is possible using reflection or get_defined_vars() and stripping out all the superglobals - but don't. Commented Jul 27, 2012 at 10:13
  • ... and is pointless. Function parameter names are irrelevant to PHP (still). Commented Jul 27, 2012 at 10:20

2 Answers 2

5

You can use get_defined_vars. An example

Sign up to request clarification or add additional context in comments.

2 Comments

Hadn't thought of that, but this means you get all defined parameters, not just the actual arguments that were passed, i.e. you will have the default values of omitted parameters in the resulting array.
@soulmerge As long as you give all arguments a default of NULL, this shouldn't matter as isset() will still return FALSE. You could always array_filter() if you want to strip them completely.
2

It can be achieved, but involves a lot of effort. You would need to get the parameter names via reflection and map the names to the values retrieved via func_get_args.

If you really need this, you can take another, simpler route and define that your function takes a single parameter object:

class MyParamObj {
    public $foo;
    public $bar;
}

function myfunc(MyParamObj $args) {
    # ...
}

1 Comment

this is a good answer that would work. @Shatki Singh's answer was more what I was looking for though

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.