如何在函数中使用无穷参数(如PHP的isset()) [英] How to work with infinity arguments in a function (like PHP's isset())
问题描述
您知道PHP的 isset()
可以接受多个(没有限制)参数吗?
可以这样做:
isset($ var1,$ var2,$ var3,$ var4,$ var5,$ var6,$ var7, $ var8,$ var9,$ var10,$ var11);
//等等
我如何能够在我自己的函数中做到这一点?我如何能够通过传递的无穷参数来工作?
他们是怎么做到的?
func_get_args
会做你想做的:
function infinite_parameters(){
foreach(func_get_args()as $ param){
echoParam is $ param。 PHP_EOL;
$ b你也可以使用 func_get_arg
得到一个特定的参数(它是零索引的):
function infinite_parameters(){
echo func_get_arg(2);
}
但请注意检查是否有该参数:
function infinite_parameters(){
if(func_num_args()< 3){
throw new BadFunctionCallException( !);
$ / code>
甚至可以将函数foo($ param1,$ param2){
echo $ param1; //正常工作
echo func_get_arg(0); //获取$ param1
if(func_num_args()> = 3){
echo func_get_arg(2);
}
}
但是在使用之前, >真的想拥有不确定的参数。数组不够用吗?
You know how PHP's isset()
can accept multiple (no limit either) arguments?
Like I can do:
isset($var1,$var2,$var3,$var4,$var5,$var6,$var7,$var8,$var9,$var10,$var11);
//etc etc
How would I be able to do that in my own function? How would I be able to work with infinity arguments passed?
How do they do it?
func_get_args
will do what you want:
function infinite_parameters() {
foreach (func_get_args() as $param) {
echo "Param is $param" . PHP_EOL;
}
}
You can also use func_get_arg
to get a specific parameter (it's zero-indexed):
function infinite_parameters() {
echo func_get_arg(2);
}
But be careful to check that you have that parameter:
function infinite_parameters() {
if (func_num_args() < 3) {
throw new BadFunctionCallException("Not enough parameters!");
}
}
You can even mix together func_*_arg
and regular parameters:
function foo($param1, $param2) {
echo $param1; // Works as normal
echo func_get_arg(0); // Gets $param1
if (func_num_args() >= 3) {
echo func_get_arg(2);
}
}
But before using it, think about whether you really want to have indefinite parameters. Would an array not suffice?
这篇关于如何在函数中使用无穷参数(如PHP的isset())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!