如何实现一个可以在PHP中使用任意参数的函数? [英] How to implement a function that can take arbitary parameters in PHP?
本文介绍了如何实现一个可以在PHP中使用任意参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
PHP有这样的功能吗?
解决方案
您可以使用这些功能:
示例:
函数my_sum(){//< ---没有参数! :D
$ total = func_num_args();
$ numbers = func_get_args();
if($ total <1){
trigger_error('少于一个数字:(');
return 0;
} else {
//计算总和
$ sum = array_sum($ numbers);
return($ sum / $ total);
}
}
//用法:
echo my_sum(1,2,5,109,10231);
?>
Does PHP has such a feature?
解决方案
You can use these functions:
- func_get_arg » http://php.net/manual/en/function.func-get-arg.php
- func_get_args » http://php.net/manual/en/function.func-get-args.php
- fung_num_args » http://php.net/manual/en/function.func-num-args.php
Example:
function my_sum() { // <--- No parameters! :D
$total = func_num_args();
$numbers = func_get_args();
if ($total < 1) {
trigger_error('Less than one number :(');
return 0;
} else {
// Calculate the sum
$sum = array_sum($numbers);
return ($sum / $total);
}
}
// Usage:
echo my_sum(1, 2, 5, 109, 10231);
?>
这篇关于如何实现一个可以在PHP中使用任意参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文