如何将可变数量的参数传递给PHP函数 [英] How to pass variable number of arguments to a PHP function

查看:137
本文介绍了如何将可变数量的参数传递给PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP函数,该函数接受可变数量的参数(使用func_num_args()func_get_args()),但是我要传递给该函数的参数数量取决于数组的长度.有没有办法用可变数量的参数调用 PHP函数?

I have a PHP function that takes a variable number of arguments (using func_num_args() and func_get_args()), but the number of arguments I want to pass the function depends on the length of an array. Is there a way to call a PHP function with a variable number of arguments?

推荐答案

如果在数组中有参数,您可能会对

If you have your arguments in an array, you might be interested by the call_user_func_array function.

如果要传递的参数数量取决于数组的长度,则可能意味着您可以将它们自己打包到数组中,并将该参数用作call_user_func_array的第二个参数.

If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array.

您传递给该数组的元素将被您的函数作为不同的参数接收.

Elements of that array you pass will then be received by your function as distinct parameters.


例如,如果您具有此功能:


For instance, if you have this function :

function test() {
  var_dump(func_num_args());
  var_dump(func_get_args());
}

您可以将参数打包到一个数组中,如下所示:

You can pack your parameters into an array, like this :

$params = array(
  10,
  'glop',
  'test',
);

然后,调用函数:

call_user_func_array('test', $params);

此代码将输出:

int 3

array
  0 => int 10
  1 => string 'glop' (length=4)
  2 => string 'test' (length=4)

即3个参数;完全类似于iof函数的调用方式:

ie, 3 parameters ; exactly like iof the function was called this way :

test(10, 'glop', 'test');

这篇关于如何将可变数量的参数传递给PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆