121

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

4

10 回答 10

135

如果您将参数放在数组中,您可能会对call_user_func_array函数感兴趣。

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

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


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

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

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

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

然后,调用函数:

call_user_func_array('test', $params);

此代码将输出:

int 3

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

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

test(10, 'glop', 'test');
于 2009-09-14T16:38:40.597 回答
64

这现在可以通过 PHP 5.6.x使用 ... 运算符(在某些语言中也称为 splat 运算符):

例子:

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' ) );
于 2014-01-27T17:06:22.897 回答
51

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

因此,使用它,您可以获得您传递的所有参数:

function manyVars(...$params) {
   var_dump($params);
}
于 2014-04-18T23:33:32.670 回答
46

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)
#> }

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

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

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);
}

PHP 7开始,参数变量列表也可以强制为相同类型。

function do_something($first, int ...$all_the_others) { /**/ }
于 2015-12-10T15:49:30.437 回答
11

对于那些正在寻找一种方法的人$object->method

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

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

于 2014-01-17T19:00:42.193 回答
4

你可以打电话给它。

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

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

输出:

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

于 2009-09-14T16:45:17.180 回答
2

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

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

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

于 2016-03-01T23:33:47.180 回答
0

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

(自 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){

    }
}

从同一班级内部:

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

从一个对象的实例:

$obj = new Foo;
$obj('methodName', ['arg1', 'arg2', 'arg3'])
于 2014-03-27T11:09:48.200 回答
0

一个老问题,我知道,但是,这里的答案都不能很好地简单地回答这个问题。

我刚刚玩过php,解决方案如下所示:

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

这个函数可以做两件事:

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

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

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

于 2015-02-02T16:25:38.890 回答
0

我想知道,我找不到有关将命名参数(自PHP 8起)与变量参数结合使用的可能性的文档。因为我尝试了这段代码,我很惊讶,它确实有效:

function myFunc(...$args) {
    foreach ($args as $key => $arg) {
        echo "Key: $key Arg: $arg <br>";
    }
}
echo myFunc(arg1:"foo", arg2:"bar");

输出:

Key: arg1 Arg: foo
Key: arg2 Arg: bar

在我看来,这很酷。

于 2021-05-20T22:05:58.777 回答