可能重复:
PHP将所有参数都作为数组?
嗯,
在java中,我可以这样做(伪代码):
public hello( String..args ){
value1 = args[0]
value2 = args[1]
...
valueN = arg[n];
}
然后:
hello('first', 'second', 'no', 'matter', 'the', 'size');
php中有类似的内容吗?
编辑
我现在可以传递一个像hello(array(bla, bla))
这样的数组,但可能会以上面提到的方式存在,对吧?
参见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);
编辑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
如果我想要一个特定的变量,我可以忽略其他变量:
function bar()
{
list($first, , $third) = func_get_args();
return $first + $third;
}
echo bar(10, 21, 37); // Output: 47