假设有一个带有某些参数的函数,并且我有一个关联数组(或者一个具有公共属性的简单对象--这几乎是相同的,因为我总是可以使用类型cast (object)$array),其键对应于函数参数名称,其值对应于函数调用参数。我怎么叫它然后把它们传进去?
<?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发布于 2020-12-27 03:19:46
发布于 2020-12-27 05:48:25
作为PHP旧版本的黑客,您还可以使用反射:
<?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);https://stackoverflow.com/questions/65462451
复制相似问题