1, "x" => 2); ...">

PHP call function with parameter using array

function myFunc($x, $y) { echo "x : {$x}"; echo "y : {$y}"; } $params = array("y" => 1, "x" => 2); 

Is it possible to call myFunc using the call_user_func_array function, but the array keys will automatically set the correct parameter in the function? Is there any function for this or can this function be created? eg:

 call_func('myFunc', $params); 

and the result will be like

 x : 2 y : 1 

Thanks.

+4
source share
2 answers

There may be an easier way to do this, but reflection should also work:

 function call_func_keys($functionName, $args) { $f = new ReflectionFunction($functionName); $inOrder = array(); foreach($f->getParameters() as $param) { if(array_key_exists($param->name, $args)) { $inOrder[] = $args[$param->name]; } else { $inOrder[] = $param->getDefaultValue(); # Will throw a reflection exception if not optional } } call_user_func_array($functionName, $inOrder); } 

Here is a demo.

+7
source

UPDATED!

Usually you should use call_user_func_array .

And it should be used as follows:

 function myFunc($x, $y) { echo "x : {$x}"; echo "y : {$y}"; } $params = array("y" => 1, "x" => 2); call_user_func_array('myFunc', $params); 

But in your case, you are definitely using Reflection . @Minitech's answer is just great.

+1
source

All Articles