Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a PHP function expecting varargs a string?

I have a PHP function which takes a variable number of arguments.

function foo() {
     $numargs = func_num_args(); 
     if ($numargs < 3) {
         die("expected number of args is 3, not " . $numargs);
     }  
...

If I call it like this:

   foo(1, 12, 17, 3, 5); 

it's fine, but if I call it like this:

   $str = "1, 12, 17, 3, 5"; 
   foo($str); 

it fails because it says I am only passing one argument. What change do I need to make if I would prefer not to change the function itself, just the calling convention.

-- update: to save the explode call, I simply built an array. And because the function was a member function, the calling convention was a bit different. So the code wound up being

$list = array(); 
$list[] = 1;
$list[] = 12;
$list[] = 17;
// etc. 
call_user_func_array(array($this, 'foo'), $list);

Thought this might be useful to someone else.

like image 627
Scott C Wilson Avatar asked Mar 03 '26 03:03

Scott C Wilson


1 Answers

This should do the trick:

$str = "1, 12, 17, 3, 5"; 
$params = explode(', ', $str );
call_user_func_array ( 'foo', $params );

call_user_func_array() allows you to call a function and passing it arguments that are stored in a array. So array item at index 0 becomes the first parameter to the function, and so on.

http://www.php.net/manual/en/function.call-user-func-array.php

update: you will have to do some additional processing on the $params array if you wish that the arguments will be integers (they are passed as strings if you use the above snippet).

like image 195
Jan Hančič Avatar answered Mar 04 '26 20:03

Jan Hančič