I have a variable length array that I need to transpose into a list of parameters for a function.

I hope there is a neat way of doing this - but I cannot see how.

The code that I am writing will be calling a method in a class - but I will not know the name of the method, nor how many parameters it has.

I tried this - but it doesn't work:

$params = array(1 => "test", 2 => "test2", 3 => "test3");
ClassName::$func_name(implode($params, ","));

The above lumps all of the values into the first parameter of the function. Whereas it should be calling the function with 3 parameter values (test, test2, test3).

What I need is this:

ClassName::$func_name("test", "test2", "test3");

Any ideas how to do this neatly?

share|improve this question

3 Answers

up vote 8 down vote accepted

Yes, use call_user_func_array():

call_user_func_array('function_name', $parameters_array);

You can use this to call methods in a class too:

class A {
  public function doStuff($a, $b) {
    echo "[$a,$b]\n";
  }
}

$a = new A;
call_user_func_array(array($a, 'doStuff'), array(23, 34));
share|improve this answer
Cletus - Thanks!! This worked a treat. I hope all the hair I pulled out will grow back :-) – Byrl Nov 25 '09 at 0:13

Use func_get_args inside the function: http://php.net/func%5Fget%5Fargs

Edit:

Even easier - why not just pass the $params array directly to the function, then have the function handle an array?

share|improve this answer

You could use eval:

  eval("$func_name(" . implode($params, ",") . ");");

Though you might need to do some lambda trickery to get your parameters quoted and/or escaped:

  $quoted_escaped_params = array_map(create_function('$a', 'return "\"". str_replace("\"",` "\\\"", $a) . "\""'), $params);
share|improve this answer
Yeah - Thanks Frank! I tried this but got bogged down with the quoting of the array values. bit messy... – Byrl Nov 25 '09 at 0:12

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.