那么,
在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))
这样的数组,但可能会以上面的方式存在,对吗?
答案 0 :(得分: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);
编辑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