Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function associative variables [duplicate]

I want to call an anonymous function (lambda or closure) which has some arguments, I know the argument names but I don't know their order! The call_user_func_array() function can call the function with an array of arguments but the array cannot be an associative array to set every value for desired argument, following codes are my attempts to solve my problem but they just don't work!

The function:

$function = function ($b, $c, $a) {
    echo "a=" . $a . " & b=" . $b . " & c=" . $c;
};

My desired output:

a=1 & b=2 & c=3

My attempts:

// Attempt 1
call_user_func_array($function, array("a" => 1, "b" => 2, "c" => 3));
// Attempt 2
$ref = new ReflectionFunction($function);
$ref->invokeArgs(array("a" => 1, "b" => 2, "c" => 3));

The yield output:

a=3 & b=1 & c=2
like image 212
Milad Rahimi Avatar asked Dec 13 '25 00:12

Milad Rahimi


1 Answers

You have to pass the parameters positionally, names aren't considered at all. You can map the parameters by name to their position using reflection:

$params = array("a" => 1, "b" => 2, "c" => 3);
$ref = new ReflectionFunction($function);

$arguments = array_map(
    function (ReflectionParameter $param) use ($params) {
        if (isset($params[$param->getName()])) {
            return $params[$param->getName()];
        }
        if ($param->isOptional()) {
            return $param->getDefaultValue();
        }
        throw new InvalidArgumentException('Missing parameter ' . $param->getName());
    },
    $ref->getParameters()
);

$ref->invokeArgs($arguments);
like image 138
deceze Avatar answered Dec 15 '25 12:12

deceze