php函数中的动态参数

man*_*nix 6 php arguments function dynamic

可能重复:
PHP将所有参数都作为数组获取?

好,

在java中,我可以这样做(伪代码):

public hello( String..args ){
    value1 = args[0] 
    value2 = args[1] 
    ...
    valueN = arg[n];
}
Run Code Online (Sandbox Code Playgroud)

然后:

hello('first', 'second', 'no', 'matter', 'the', 'size');
Run Code Online (Sandbox Code Playgroud)

在PHP中是这样的吗?

编辑

我现在可以传递一个类似的数组hello(array(bla, bla)),但可能存在于上面的方式,对吗?

Gab*_*tos 27

func_get_args:

function foo()
{
    $numArgs = func_num_args();

    echo 'Number of arguments:' . $numArgs . "\n";

    if ($numArgs >= 2) {
        echo 'Second argument is: ' . func_get_arg(1) . "\n";
    }

    $args = func_get_args();
    foreach ($args as $index => $arg) {
        echo 'Argument' . $index . ' is ' . $arg . "\n";

        unset($args[$index]);
    }
}

foo(1, 2, 3);
Run Code Online (Sandbox Code Playgroud)

编辑1

当你打电话时foo(17, 20, 31) func_get_args(),不知道第一个参数代表$first变量.当您知道每个数字索引代表什么时,您可以执行此操作(或类似):

function bar()
{
    list($first, $second, $third) = func_get_args();

    return $first + $second + $third;
}

echo bar(10, 21, 37); // Output: 68
Run Code Online (Sandbox Code Playgroud)

如果我想要一个特定的变量,我可以省略其他变量:

function bar()
{
    list($first, , $third) = func_get_args();

    return $first + $third;
} 

echo bar(10, 21, 37); // Output: 47
Run Code Online (Sandbox Code Playgroud)

  • 你是如此快速的愤怒:D这是我正在寻找的东西.谢谢!和其他人一样 (3认同)
  • 这个答案已经过时了。从 PHP 5.6 开始,您可以使用 [可变长度参数列表](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new) (2认同)