3

我有一个 PHP 函数,它接受可变数量的参数。

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

如果我这样称呼它:

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

没关系,但如果我这样称呼它:

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

它失败了,因为它说我只传递了一个论点。如果我不想更改函数本身,只更改调用约定,我需要进行哪些更改。

--更新:为了保存explode调用,我简单地构建了一个数组。而且因为该函数是一个成员函数,所以调用约定有点不同。所以代码最终是

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

认为这可能对其他人有用。

4

2 回答 2

4

这应该可以解决问题:

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

call_user_func_array()允许您调用函数并传递存储在数组中的参数。因此,索引 0 处的数组项成为函数的第一个参数,依此类推。

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

于 2013-03-12T14:14:12.810 回答
3
$str = "1, 12, 17, 3, 5"; 
call_user_func_array('foo',explode(',',$str));
于 2013-03-12T14:14:09.960 回答