我确定必须有办法做到这一点:
我想要它,如果我调用这样的函数...
callFunction("var1","var2","var3");
Run Code Online (Sandbox Code Playgroud)
函数'callFunction'会将这些变量转换为数组,即:
$array[0] = "var1";
$array[1] = "var2";
$array[2] = "var3";
Run Code Online (Sandbox Code Playgroud)
我希望它生成这个数组,无论调用函数时列出了多少变量,这可能吗?
您可以简单地执行以下操作:
function callFunction() {
$arr = func_get_args();
// Do something with all the arguments
// e.g. $arr[0], ...
}
Run Code Online (Sandbox Code Playgroud)
func_get_args将返回传递给函数的所有参数.您甚至不需要在函数头中指定它们.
func_num_args将产生传递给函数的参数数量.我不完全确定为什么这样的东西存在,因为你可以简单count(func_get_args()),但我想它存在是因为它在C中存在(实际上它是必要的).
如果你再次用不同的语言寻找这种功能,它通常被称为Variadic功能,或者如果你需要快速使用谷歌"varargs":)