9

I'm curious to know if there is some way to call a function using an associative array to declare the parameters.

For instance if I have this function:

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

Is there some way to call it doing something like this?

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

I'm familiar with using call_user_func and call_user_func_array, but I'm looking for something more generic that I can use to call various methods when I don't know what parameters they are looking for ahead of time.

Edit: The reason for this is to make a single interface for an API front end. I'm accepting JSON and converting that into an array. So, I'd like different methods to be called and pass the values from the JSON input into the methods. Since I want to be able to call an assortment of different methods from this interface, I want a way to pass parameters to the functions without knowing what order they need to be in. I'm thinking using reflections will get me the results I'm looking for.

2
  • Is there any reason why you would want to do this? Commented Mar 30, 2013 at 16:15
  • It's for an API front end. I'm accepting JSON and converting that into an array. So, I'd like different methods to be called and pass the values from the JSON input into the methods. Commented Mar 30, 2013 at 16:24

4 Answers 4

4

With PHP 5.4+, this works

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

test(['hello'=>'world', 'lorem'=>'ipsum']);
Sign up to request clarification or add additional context in comments.

Comments

3

Check the php manual for call_user_func_array

Also, look up token operator (...). It is a way to use varargs with functions in PHP. You can declare something like this: -

function func( ...$params)
{
    echo $params[0] . ',' . parama[1];
}

Comments

2

You can use this function internal in your functions func_get_args()

So, you can use it like this one:

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

test('hello', 'world');

Comments

1

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

Comments

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.