php PHP将所有参数作为数组获取?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/828709/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:59:01  来源:igfitidea点击:

PHP get all arguments as array?

phparraysfunctionarguments

提问by MiffTheFox

Hey, I was working with a PHP function that takes multiple arguments and formats them. Currently, I'm working with something like this:

嘿,我正在使用一个 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);
}

But I was wondering if I can use a solution like this:

但我想知道我是否可以使用这样的解决方案:

function foo(params $args){
    for ($i = 0; $i < count($args); $i++)
        doSomethingWith($args[$i], $i + 1);
}

But still invoke the function the same way, similar to the params keyword in C# or the arguments array in JavaScript.

但仍然以相同的方式调用函数,类似于 C# 中的 params 关键字或 JavaScript 中的参数数组。

回答by bb.

func_get_argsreturns an array with all arguments of the current function.

func_get_args返回一个包含当前函数所有参数的数组。

回答by Joren

If you use PHP 5.6+, you can now do this:

如果你使用 PHP 5.6+,你现在可以这样做:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

source: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list

来源:http: //php.net/manual/en/functions.arguments.php#functions.variable-arg-list

回答by Thielicious

Or as of PHP 7.1you are now able to use a type hint called iterable

或者从PHP 7.1 开始,您现在可以使用名为的类型提示iterable

function f(iterable $args) {
    foreach ($args as $arg) {
        // awesome stuff
    }
}

Also, it can be used instead of Traversablewhen you iterate using an interface. As well as it can be used as a generator that yields the parameters.

此外,它可以代替Traversable使用接口进行迭代时使用。它还可以用作生成参数的生成器。

Documentation

文档