Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward undefined number of arguments to another function

I will explain the question with a simple function accepting any number of function

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

}

I hope the question is clear now, what is the work around for this situation?

Update

I forgot to mention that the next function I am calling is a constructor class of another class. Something like

$newclass = new class($newarguments);
like image 329
Starx Avatar asked Jun 21 '11 07:06

Starx


Video Answer


1 Answers

for simple function calls

use call_user_func_array, but do not implode the args, just pass the array of remaining args to call_user_func_array

call_user_func_array('anotherFunction', $args);

for object creation

use: ReflectionClass::newInstanceArgs

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

or: ReflectionClass::newinstance

$refClass = new ReflectionClass('yourClassName');
$obj = call_user_func_array(array($refClass, 'newInstance'), $yourConstructorArgs);
like image 66
Yoshi Avatar answered Sep 23 '22 19:09

Yoshi