PHP 函数可以接受无限数量的参数吗? [英] Can a PHP function accept an unlimited number of parameters?
问题描述
在 PHP 中有像 unset()
这样的函数,它们支持我们向它们抛出的任意数量的参数.
In PHP there are functions like unset()
that support any number of parameter we throw at them.
我想创建一个类似的函数,它能够接受任意数量的参数并处理它们.
I want to create a similar function that is capable of accepting any number of parameters and process them all.
知道怎么做吗?
推荐答案
在 PHP 中,使用函数 func_get_args
获取所有传递的参数.
In PHP, use the function func_get_args
to get all passed arguments.
<?php
function myfunc(){
$args = func_get_args();
foreach ($args as $arg)
echo $arg."/n";
}
myfunc('hello', 'world', '.');
?>
另一种方法是将变量数组传递给您的函数,这样您就不必使用诸如 $arg[2];
之类的东西,而可以使用 $args['myvar'];
或重新记住事物传入的顺序.它还可以无限扩展,这意味着您可以在以后添加新变量而无需更改您已经编码的内容.
An alternative is to pass an array of variables to your function, so you don't have to work with things like $arg[2];
and instead can use $args['myvar'];
or rewmember what order things are passed in. It is also infinitely expandable which means you can add new variables later without having to change what you've already coded.
<?php
function myfunc($args){
while(list($var, $value)=each($args))
echo $var.' '.$value."/n";
}
myfunc(array('first'=>'hello', 'second'=>'world', '.'));
?>
这篇关于PHP 函数可以接受无限数量的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!