将多个参数传递给函数 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16823611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing multiple arguments to function php
提问by Undermine2k
Apologies for the newbie question but i have a function that takes two parameters one is an array one is a variable function createList($array, $var) {}
. I have another function which calls createList with only one parameter, the $var, doSomething($var);
it does not contain a local copy of the array. How can I just pass in one parameter to a function which expects two in PHP?
为新手问题道歉,但我有一个函数需要两个参数,一个是数组,一个是变量function createList($array, $var) {}
。我有另一个函数,它只使用一个参数 $var 调用 createList,doSomething($var);
它不包含数组的本地副本。如何只将一个参数传递给一个在 PHP 中需要两个参数的函数?
attempt at solution :
尝试解决:
function createList (array $args = array()) {
//how do i define the array without iterating through it?
$args += $array;
$args += $var;
}
采纳答案by Orangepill
You have a couple of options here.
你有几个选择。
First is to use optional parameters.
首先是使用可选参数。
function myFunction($needThis, $needThisToo, $optional=null) {
/** do something cool **/
}
The other way is just to avoid naming any parameters (this method is not preferred because editors can't hint at anything and there is no documentation in the method signature).
另一种方法只是避免命名任何参数(这种方法不是首选,因为编辑器不能暗示任何东西并且方法签名中没有文档)。
function myFunction() {
$args = func_get_args();
/** now you can access these as $args[0], $args[1] **/
}
回答by Petruza
If you can get your hands on PHP 5.6+, there's a new syntax for variable arguments: the ellipsis keyword.
It simply converts all the arguments to an array.
如果您可以使用 PHP 5.6+,那么变量参数有一个新的语法:省略号关键字。
它只是将所有参数转换为数组。
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
Doc: ... in PHP 5.6+
回答by crush
You can specify no parameters in your function declaration, then use PHP's func_get_argor func_get_argsto get the arguments.
您可以在函数声明中不指定参数,然后使用 PHP 的func_get_arg或func_get_args来获取参数。
function createList() {
$arg1 = func_get_arg(0);
//Do some type checking to see which argument it is.
//check if there is another argument with func_num_args.
//Do something with the second arg.
}