PHP get all function arguments as $key => $value array?

PHP does not support an arbitrary number of named parameters. You either decide on a fixed number of parameters and their names in the function declaration or you can only get values.

The usual way around this is to use an array:

function register_template($args) {
    // use $args
}

register_template(array('name' => 'my template', ...));

Wanted to do the same thing and wasn't completely satisfied with the answers already given....

Try adding this into your function ->

$reflector = new ReflectionClass(__CLASS__);
$parameters = $reflector->getMethod(__FUNCTION__)->getParameters();

$args = array();
foreach($parameters as $parameter)
{
    $args[$parameter->name] = ${$parameter->name};
}
print_r($args);

I haven't thought about trying to make this it's own function yet that you can just call, but might be able to...


There is no such thing as a parameter name. frobnicate($a = "b") is not a call-with-parameter syntax, it's merely an assignment followed by a function call - a trick used for code documentation, not actually taken into account by the language.

It is commonly accepted to instead provide an associative array of parameters in the form: frobnicate(array('a' => 'b'))

Tags:

Php