PHP:数组变量函数的参数值 [英] PHP: Array to variable function parameter values
问题描述
我有一个可变长度的数组,我需要转成一个函数的参数列表。
I have a variable length array that I need to transpose into a list of parameters for a function.
我希望有这样的一种巧妙的方法 - 但我不能看到如何
I hope there is a neat way of doing this - but I cannot see how.
在code,我写会调用一个类的方法 - 但我不知道该方法的名称,也没有多少参数,它有。
The code that I am writing will be calling a method in a class - but I will not know the name of the method, nor how many parameters it has.
我想这一点 - 但它不工作:
I tried this - but it doesn't work:
$params = array(1 => "test", 2 => "test2", 3 => "test3");
ClassName::$func_name(implode($params, ","));
上面的团块的所有值到函数的第一个参数。而应该调用带有3个参数值(测试,TEST2,TEST3)。
The above lumps all of the values into the first parameter of the function. Whereas it should be calling the function with 3 parameter values (test, test2, test3).
我需要的是这样的:
ClassName::$func_name("test", "test2", "test3");
任何想法如何巧妙地做到这一点?
Any ideas how to do this neatly?
推荐答案
是,使用<一个href=\"http://www.php.net/manual/en/function.call-user-func-array.php\"><$c$c>call_user_func_array()$c$c>:
call_user_func_array('function_name', $parameters_array);
您可以用它来调用一个类的方法太:
You can use this to call methods in a class too:
class A {
public function doStuff($a, $b) {
echo "[$a,$b]\n";
}
}
$a = new A;
call_user_func_array(array($a, 'doStuff'), array(23, 34));
这篇关于PHP:数组变量函数的参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!