Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

<?php
function register_template(){
    print_r(func_get_args());
    # the result was an array ( [0] => my template [1] => screenshot.png [2] => nice template .. ) 

}

register_template(     # unkown number of arguments
    $name = "my template",
    $screenshot = "screenshot.png",
    $description = "nice template .. "
)
?>

BUT , I want the result array as $key => $value form , $key represents the parameter name.

like image 362
web lover Avatar asked Jan 13 '11 09:01

web lover


2 Answers

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', ...));
like image 74
deceze Avatar answered Sep 26 '22 00:09

deceze


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...

like image 36
user1462432 Avatar answered Sep 26 '22 00:09

user1462432