Pass an associative array of function to PHP

I am interested to know if there is a way to call a function using an associative array to declare parameters.

For example, if I have this function:

function test($hello, $world) {
    echo $hello . $world;
}

Is there any way to call it something like this?

call('test', array('hello' => 'First value', 'world' => 'Second value'));

I am familiar with using call_user_funcand call_user_func_array, but I am looking for something more general that I can use to call various methods when I do not know what parameters they are looking ahead of time.

Edit: The reason for this is to create a single interface for the API. I accept JSON and convert it to an array. Thus, I would like various methods to be called and pass values ​​from JSON input to methods. Since I want to be able to call a set of different methods from this interface, I want to pass parameters to functions without knowing in what order they should be. I think using reflections will give me results, m looking for.

+5
source share
4 answers

Check php manual for call_user_func_array

+3
source

You can use this function in your func_get_args () functions

So you can use it like this:

function test() {
     $arg_list = func_get_args();
     echo $arg_list[0].' '.$arg_list[1]; 
}

test('hello', 'world');
+2
source

With PHP 5.4+ this works

function test($assocArr){
  foreach( $assocArr as $key=>$value ){
    echo $key . ' ' . $value . ' ';
  }
}

test(['hello'=>'world', 'lorem'=>'ipsum']);
+2
source

The following should work ...

function test($hello, $world) {
  echo $hello . $world;
}

$callback = 'test'; <-- lambdas also work here, BTW

$parameters = array('hello' => 'First value', 'world' => 'Second value');

$reflection = new ReflectionFunction($callback);
$new_parameters = array();

foreach ($reflection->getParameters() as $parameter) {
  $new_parameters[] = $parameters[$parameter->name];
}

$parameters = $new_parameters;

call_user_func_array($callback, $parameters);
0
source

All Articles