parameter passing - How to use a PHP associative array as function call arguments?
Get the solution ↓↓↓Assume that there is a function with some parameters and I have an associative array (or a simple object with public properties - which is almost the same, since I can always use a type cast(object)$array
) whose keys correspond to the function parameter names and whose values correspond to function call arguments. How do I call it and pass them in there?
<?php
function f($b, $a) { echo "$a$b"; }
// notice that the order of args may differ.
$args = ['a' => 1, 'b' => 2];
call_user_func_array('f', $args); // expected output: 12 ; actual output: 21
f($args); // expected output: 12 ; actual output: ↓
// Fatal error: Uncaught ArgumentCountError:
// Too few arguments to function f(), 1 passed
Answer
Solution:
It turns out, I just had to use variadic function named param unpacking feature introduced in PHP 8 ( https://wiki.php.net/rfc/named_params#variadic_functions_and_argument_unpacking ) :
f(...$args); // output: 12
Prior to PHP 8, this code produces the error:Cannot unpack array with string keys
.
Secondly, it turns out thatcall_user_func_array
also works as expected in PHP 8 (see https://wiki.php.net/rfc/named_params#call_user_func_and_friends for explanation):
call_user_func_array('f', $args); // output: 12
- while it still outputs incorrect '21' in older versions.
Answer
Solution:
As a hack for older versions of PHP you could also use Reflection:
<?php
function test($b, $a) {
echo "$a$b";
}
$callback = 'test';
$parameters = ['a' => 1, 'b' => 2];
$reflection = new ReflectionFunction($callback);
$new_parameters = array();
foreach ($reflection->getParameters() as $parameter) {
$new_parameters[] = $parameters[$parameter->name];
}
$parameters = $new_parameters;
call_user_func_array($callback, $parameters);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.