[英]Call a function with dynamic list of vars PHP
Let say i have function: 假设我有功能:
<?php
function myFunction($param1, $param2, /*0 or more extra args*/) {
// do something with $param1 & $param2
$args = func_get_args();
$other_args = array_slice($args, 2); // get the dynamic args
// do something with $other_args
}
?>
this enables to call: 这样可以调用:
<?php
myFunction($param1, $param2); // or
myFunction($param1, $param2, $param3); // or
myFunction($param1, $param2, $param3, $param4);
?>
But i want to know if it possible to to take an array of args and pass them into the function eg: 但我想知道是否有可能采用args数组并将其传递给函数,例如:
<?php
$extra_args = array($param3, $param4); // this could also be
$extra_args = array($param3, $param4, $param5); // or any length array
?>
i would like to pass them as separate params into my function eg 我想将它们作为单独的参数传递给我的功能,例如
<?php
myFunction($param1, $param2 /* other args split up */);
?>
Thanks in advance! 提前致谢!
Yeap - call_user_func_array()
'. 是的-call_user_func_array
call_user_func_array()
'。
http://www.php.net/manual/en/function.call-user-func-array.php http://www.php.net/manual/zh/function.call-user-func-array.php
Takes two arguments - the function name (as a string - or possibly, in PHP >= 5.3, an anonymous function, not sure) and an array of params. 接受两个参数-函数名称(作为字符串-或可能在PHP> = 5.3中为匿名函数,不确定)和参数数组。
Or for methods, forward_static_call_array()
或对于方法,
forward_static_call_array()
http://www.php.net/manual/en/function.forward-static-call-array.php http://www.php.net/manual/zh/function.forward-static-call-array.php
PHP's answer to JS's function.prototype.apply()
:) PHP对JS的
function.prototype.apply()
的回答:)
call_user_func_array('myFunction',
array_merge(
array($param1,$param2),
$extra_args));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.