[英]Passing an array through a PHP function
Im sure there has to be a way to do this: 我确定必须有办法做到这一点:
I want it so that If I call a function like this... 我想要它,如果我调用这样的函数...
callFunction("var1","var2","var3");
the function 'callFunction' will turn these variables into an array ie: 函数'callFunction'会将这些变量转换为数组,即:
$array[0] = "var1";
$array[1] = "var2";
$array[2] = "var3";
I want it to generate this array no matter how many variables are listed when calling the function, is this possible? 我希望它生成这个数组,无论调用函数时列出了多少变量,这可能吗?
You can simply do the following: 您可以简单地执行以下操作:
function callFunction() {
$arr = func_get_args();
// Do something with all the arguments
// e.g. $arr[0], ...
}
func_get_args
will return all the parameters passed to a function. func_get_args
将返回传递给函数的所有参数。 You don't even need to specify them in the function header. 您甚至不需要在函数头中指定它们。
func_num_args
will yield the number of arguments passed to the function. func_num_args
将产生传递给函数的参数数量。 I'm not entirely sure why such a thing exists, given that you can simple count(func_get_args())
, but I suppose it exist because it does in C (where it is actually necessary). 我不完全确定为什么存在这样的事情,因为你可以简单地
count(func_get_args())
,但我认为它存在是因为它在C中存在(实际上它是必要的)。
If you ever again look for this kind of feature in a different language, it is usually referred to as Variadic Function , or "varargs" if you need to Google it quickly :) 如果你再次用不同的语言寻找这种功能,它通常被称为Variadic功能 ,或者如果你需要快速使用谷歌“varargs”:)
Just return func_get_args()
from that function: 只需从该函数返回
func_get_args()
:
function callFunction(){
return func_get_args();
}
$array = callFunction("var1","var2","var3","var4","var5");
var_dump($array);
/*array(5) {
[0]=>
string(4) "var1"
[1]=>
string(4) "var2"
[2]=>
string(4) "var3"
[3]=>
string(4) "var4"
[4]=>
string(4) "var5"
}*/
Call your function like this. 像这样调用你的功能。
callFunction( array("var1", "var2", "var3", "var4", "var5") );
and create your function like this. 并创建这样的功能。
function callFunction($array)
{
//here you can acces your array. no matter how many variables are listed when calling the function.
print_r($array);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.