将未定义的参数数量转发给另一个函数

时间:2011-06-21 07:55:49

标签: php function arguments

我将用一个接受任意数量函数的简单函数来解释这个问题

function abc() {
   $args = func_get_args();
   //Now lets use the first parameter in something...... In this case a simple echo
   echo $args[0];
   //Lets remove this first parameter 
   unset($args[0]); 

   //Now I want to send the remaining arguments to different function, in the same way as it received
   .. . ...... BUT NO IDEA HOW TO . ..................

   //tried doing something like this, for a work around
   $newargs = implode(",", $args); 
   //Call Another Function
   anotherFUnction($newargs); //This function is however a constructor function of a class
   // ^ This is regarded as one arguments, not mutliple arguments....

}

我希望现在的问题很清楚,这种情况的解决方法是什么?

更新

我忘了提到我调用的下一个函数是另一个类的构造函数类。 像

这样的东西
$newclass = new class($newarguments);

1 个答案:

答案 0 :(得分:12)

用于简单的函数调用

使用call_user_func_array,但不破坏 args,只需将剩余参数数组传递给call_user_func_array

call_user_func_array('anotherFunction', $args);

用于创建对象

使用:ReflectionClass::newInstanceArgs

$refClass = new ReflectionClass('yourClassName');
$obj = $refClass->newInstanceArgs($yourConstructorArgs);

或:ReflectionClass::newinstance

$refClass = new ReflectionClass('yourClassName');
$obj = call_user_func_array(array($refClass, 'newInstance'), $yourConstructorArgs);