tags:

views:

736

answers:

2

I have a PHP function that takes a variable number of arguments (using func_num_args() and func_get_args()), but the number of arguments I want to pass the function depends on the length of an array. Is there a way to call a PHP function with a variable number of arguments?

+7  A: 

Hi,

If you have your arguments in an array, you might be interested by the call_user_func_array function.

If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array.

Elements of that array you pass will then be received by your function as distinct parameters.


For instance, if you have this function :

function test() {
  var_dump(func_num_args());
  var_dump(func_get_args());
}

You can pack your parameters into an array, like this :

$params = array(
  10,
  'glop',
  'test',
);

And, then, call the function :

call_user_func_array('test', $params);

This code will the output :

int 3

array
  0 => int 10
  1 => string 'glop' (length=4)
  2 => string 'test' (length=4)

ie, 3 parameters ; exactly like iof the function was called this way :

test(10, 'glop', 'test');
Pascal MARTIN
Yes, thank you. call_user_func_array() is exactly the function I was looking for.
nohat
Is it possible to use call_user_func_array() with an object method call?
nohat
@nohat : you're welcome :-) ;; about using a method of an object : yes, you can, using something like array($obj, 'methodName') as first parameter ;; actually, you can pass any "callback" you want to that function. For more informations about callbacks, see http://php.net/callback#language.types.callback
Pascal MARTIN
A: 

You can just call it.

function test(){        
     print_r(func_get_args());
}

test("blah");
test("blah","blah");

Output:

Array ( [0] => blah ) Array ( [0] => blah [1] => blah )

Donnie C
If I understand the OP correctly, the problem is not receiving the parameters, but **calling the function** with a variable number of parameters.
Pascal MARTIN
I didn't understanding the OP correctly, then. An array would definitely be the way to go, then. Then again, he could just pass the array directly into test(), no?
Donnie C
Passing an array might be a solution too, indeed -- If I understood correctly ^^
Pascal MARTIN