Mif*_*Fox 33 php arrays arguments function
嘿,我正在使用PHP函数,它接受多个参数并格式化它们.目前,我正在使用这样的东西:
function foo($a1 = null, $a2 = null, $a3 = null, $a4 = null){
if ($a1 !== null) doSomethingWith($a1, 1);
if ($a2 !== null) doSomethingWith($a2, 2);
if ($a3 !== null) doSomethingWith($a3, 3);
if ($a4 !== null) doSomethingWith($a4, 4);
}
Run Code Online (Sandbox Code Playgroud)
但我想知道我是否可以使用这样的解决方案:
function foo(params $args){
for ($i = 0; $i < count($args); $i++)
doSomethingWith($args[$i], $i + 1);
}
Run Code Online (Sandbox Code Playgroud)
但仍然以相同的方式调用函数,类似于C#中的params关键字或JavaScript中的arguments数组.
小智 76
func_get_args
返回一个包含当前函数的所有参数的数组.
Jor*_*ren 11
如果您使用PHP 5.6+,现在可以执行以下操作:
<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
Run Code Online (Sandbox Code Playgroud)
来源:http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
或者从PHP 7.1开始,您现在可以使用名为的类型提示iterable
function f(iterable $args) {
foreach ($args as $arg) {
// awesome stuff
}
}
Run Code Online (Sandbox Code Playgroud)
此外,它可以代替Traversable
使用接口迭代时使用.它也可以用作产生参数的发电机.