Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Array to variable function parameter values

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?

like image 501
Byrl Avatar asked Nov 24 '09 23:11

Byrl


People also ask

How do you pass an array as a function argument in PHP?

php function title($title, $name) { return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); $myArray = array('Dr', 'Phil'); echo $function->invokeArgs($myArray); // prints "Dr.

How do you get the number of arguments passed to a PHP function?

To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you.

Can a parameter be an array?

A parameter array can be used to pass an array of arguments to a procedure. You don't have to know the number of elements in the array when you define the procedure. You use the ParamArray keyword to denote a parameter array.

Does PHP pass by reference or value?

PHP variables are assigned by value, passed to functions by value and when containing/representing objects are passed by reference.


1 Answers

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));
like image 133
cletus Avatar answered Sep 18 '22 02:09

cletus