如何将可变数量的参数传递给 PHP 函数

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

How to pass variable number of arguments to a PHP function

phpvariadic-functions

提问by nohat

I have a PHP function that takes a variable number of arguments (using func_num_args()and func_get_args()), but the number of arguments I want to pass the function depends on the length of an array. Is there a way to calla PHP function with a variable number of arguments?

我有一个 PHP 函数,它接受可变数量的参数(使用func_num_args()func_get_args()),但我想传递函数的参数数量取决于数组的长度。有没有办法用可变数量的参数调用PHP 函数?

回答by Pascal MARTIN

If you have your arguments in an array, you might be interested by the call_user_func_arrayfunction.

如果你的参数在一个数组中,你可能会对这个call_user_func_array函数感兴趣。

If the number of arguments you want to pass depends on the length of an array, it probably means you can pack them into an array themselves -- and use that one for the second parameter of call_user_func_array.

如果要传递的参数数量取决于数组的长度,这可能意味着您可以自己将它们打包到一个数组中——并将该参数用于call_user_func_array.

Elements of that array you pass will then be received by your function as distinct parameters.

然后,您传递的该数组的元素将作为不同的参数被您的函数接收。


For instance, if you have this function :


例如,如果你有这个功能:

function test() {
  var_dump(func_num_args());
  var_dump(func_get_args());
}

You can pack your parameters into an array, like this :

您可以将参数打包到一个数组中,如下所示:

$params = array(
  10,
  'glop',
  'test',
);

And, then, call the function :

然后,调用函数:

call_user_func_array('test', $params);

This code will the output :

此代码将输出:

int 3

array
  0 => int 10
  1 => string 'glop' (length=4)
  2 => string 'test' (length=4)

ie, 3 parameters ; exactly like iof the function was called this way :

即,3 个参数;就像 iof 函数被这样调用一样:

test(10, 'glop', 'test');

回答by JCM

This is now possible with PHP 5.6.x, using the ... operator (also known as splat operator in some languages):

现在可以在 PHP 5.6.x中使用 ... 操作符(在某些语言中也称为 splat 操作符):

Example:

例子:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}

addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ), 
        new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );

回答by Salvador Dali

In a new Php 5.6, you can use ... operatorinstead of using func_get_args().

在新的Php 5.6 中,您可以使用... operator而不是使用func_get_args().

So, using this, you can get all the parameters you pass:

所以,使用这个,你可以得到你传递的所有参数:

function manyVars(...$params) {
   var_dump($params);
}

回答by Daniele Orlando

Since PHP 5.6, a variable argument list can be specified with the ...operator.

PHP 5.6 起,可以使用...运算符指定可变参数列表。

function do_something($first, ...$all_the_others)
{
    var_dump($first);
    var_dump($all_the_others);
}

do_something('this goes in first', 2, 3, 4, 5);

#> string(18) "this goes in first"
#>
#> array(4) {
#>   [0]=>
#>   int(2)
#>   [1]=>
#>   int(3)
#>   [2]=>
#>   int(4)
#>   [3]=>
#>   int(5)
#> }

As you can see, the ...operator collects the variable list of arguments in an array.

如您所见,该...运算符收集数组中的变量变量列表。

If you need to pass the variable arguments to another function, the ...can still help you.

如果您需要将变量参数传递给另一个函数,...仍然可以帮助您。

function do_something($first, ...$all_the_others)
{
    do_something_else($first, ...$all_the_others);
    // Which is translated to:
    // do_something_else('this goes in first', 2, 3, 4, 5);
}


Since PHP 7, the variable list of arguments can be forced to be allof the same type too.

由于PHP 7,可变参数列表可以强制为所有同类型的了。

function do_something($first, int ...$all_the_others) { /**/ }

回答by danilo

For those looking for a way to do this with $object->method:

对于那些正在寻找一种方法来做到这一点的人$object->method

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

我在一个构造函数中成功地做到了这一点,该函数调用带有可变参数的变量 method_name。

回答by Donnie C

You can just call it.

你可以直接调用它。

function test(){        
     print_r(func_get_args());
}

test("blah");
test("blah","blah");

Output:

输出:

Array ( [0] => blah ) Array ( [0] => blah [1] => blah )

数组 ( [0] => 等等 ) 数组 ( [0] => 等等 [1] => 等等 )

回答by iautomation

I'm surprised nobody here has mentioned simply passing and extracting an array. E.g:

我很惊讶这里没有人提到简单地传递和提取数组。例如:

function add($arr){
    extract($arr, EXTR_REFS);
    return $one+$two;
}
$one = 1;
$two = 2;
echo add(compact('one', 'two')); // 3

Of course, this does not provide argument validation. For that, anyone can use my expect function: https://gist.github.com/iautomation/8063fc78e9508ed427d5

当然,这不提供参数验证。为此,任何人都可以使用我的期望功能:https: //gist.github.com/iautomation/8063fc78e9508ed427d5

回答by Alex

An old question, I know, however, none of the answers here really do a good job of simply answer the question.

然而,我知道一个老问题,这里没有一个答案能很好地简单回答这个问题。

I just played around with php and the solution looks like this:

我只是玩弄 php,解决方案如下所示:

function myFunction($requiredArgument, $optionalArgument = "default"){
   echo $requiredArgument . $optionalArgument;
}

This function can do two things:

这个函数可以做两件事:

If its called with only the required parameter: myFunction("Hi")It will print "Hi default"

如果它只使用必需的参数调用:myFunction("Hi")它将打印“Hi default”

But if it is called with the optional parameter: myFunction("Hi","me")It will print "Hi me";

但是如果用可选参数调用myFunction("Hi","me")它:它会打印“Hi me”;

I hope this helps anyone who is looking for this down the road.

我希望这可以帮助任何正在寻找这个的人。

回答by Dieter Gribnitz

Here is a solution using the magic method __invoke

这是使用魔术方法 __invoke 的解决方案

(Available since php 5.3)

(自 php 5.3 起可用)

class Foo {
    public function __invoke($method=null, $args=[]){
        if($method){
            return call_user_func_array([$this, $method], $args);
        }
        return false;
    }

    public function methodName($arg1, $arg2, $arg3){

    }
}

From inside same class:

来自同一个班级:

$this('methodName', ['arg1', 'arg2', 'arg3']);

From an instance of an object:

从对象的实例:

$obj = new Foo;
$obj('methodName', ['arg1', 'arg2', 'arg3'])