如何使用 PHP 关联数组作为函数调用参数?

why*_*yer 4 php associative-array parameter-passing function-call

假设有一个带有一些参数的函数,并且我有一个关联数组(或一个具有公共属性的简单对象 - 这几乎是相同的,因为我总是可以使用类型转换(object)$array),其键对应于函数参数名称及其值对应于函数调用参数。我如何调用它并将它们传递到那里?

\n
<?php\nfunction f($b, $a) { echo "$a$b"; }\n// notice that the order of args may differ.\n$args = ['a' => 1, 'b' => 2];\ncall_user_func_array('f', $args); // expected output: 12 ; actual output: 21\nf($args); // expected output: 12 ; actual output: \xe2\x86\x93\n// Fatal error: Uncaught ArgumentCountError:\n// Too few arguments to function f(), 1 passed\n
Run Code Online (Sandbox Code Playgroud)\n

why*_*yer 5

事实证明,我只需要使用 PHP 8 中引入的名为 param 解包功能的可变参数函数(https://wiki.php.net/rfc/named_pa ​​rams#variadic_functions_and_argument_unpacking):

f(...$args); // output: 12
Run Code Online (Sandbox Code Playgroud)

在 PHP 8 之前,此代码会产生错误:Cannot unpack array with string keys

其次,事实证明它call_user_func_array在 PHP 8 中也能按预期工作(有关解释,请参阅https://wiki.php.net/rfc/named_pa ​​rams#call_user_func_and_friends ):

call_user_func_array('f', $args); // output: 12
Run Code Online (Sandbox Code Playgroud)

- 虽然它在旧版本中仍然输出不正确的“21”。