Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP call function with parameter using array

Tags:

php

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

Is it possible to call myFunc like using call_user_func_array function but the keys of array will automatically set the right parameter in the function? Is there any function to do this or is it possible to create this function? for example :

call_func('myFunc', $params);

and the result would be like this

x : 2
y : 1

Thanks.

like image 637
Darwin Gautalius Avatar asked Feb 18 '23 06:02

Darwin Gautalius


1 Answers

There might be a simpler way to do this, but reflection should work too:

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's a demo.

like image 173
Ry- Avatar answered Feb 27 '23 09:02

Ry-