我将所有调用都传递给一个主映射函数 然后它应该根据字符串动态调用其他函数(直到这一部分,事情很简单) 问题是我想将参数传递给第二个函数,这些参数可能会有所不同。 给出以下内容(不应更改):
function test1($x){
echo $x;
}
function test2($x, $y){
echo $x * $y;
}
现在是映射函数
function mapping ($str){
switch ($str){
case 'name1':
$fn_name = 'test1';
$var = 5;
break;
case 'name2':
$fn_name = 'test2';
$var = 5;
break;
}
$this->{$fn_name}($var);
}
然后这将运行映射:
$this->mapping('name1');
$this->mapping('name2'); // This one will crash as it need two variables
当然,上面的简化是为了关注问题而不是代码的目的。
问题是当函数有多个参数时(这很容易发生)。
我期待有开关案例,并根据案例参数的填充方式,该行
$this->{$fn_name}($var);
应该可以。
知道函数 (test1, test2) 结构不能更改,能否请您提出建议或给我一些想法。我不能突然开始使用 func_get_args()
或 func_get_arg()
最佳答案
您可以使用 ReflectionFunction及其 invokeArgs()
在数组中传递变量的方法:
function mapping ($str) {
switch ($str) {
case 'name1':
$fn_name = 'test1';
$fn_args = array(5);
break;
case 'name2':
$fn_name = 'test2';
$fn_args = array(5, 10);
break;
}
$function = new ReflectionFunction($fn_name);
$function->invokeArgs($fn_args);
}
关于php - 动态函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061041/