奇妙的可缩短的参数列表
上述页面中的所有例子都有一个共同点:函数定义的参数数目是固定的。然而,PHP 4.x通过使用func_num_args()和func_get_args()命令也支持变长参数列表。因为想要更好的名称,所以这些函数被称为“函数的函数”。当你学习下一例子的时候,请试着将精力集中在那些函数上,该例子解释了这些函数是如何使用的:
<?php // define a function function someFunc() { // get the arguments $args = func_get_args(); // print the arguments print "You sent me the following arguments:"; foreach ($args as $arg) { print " $arg "; } print "<br />"; } // call a function with different arguments someFunc("red", "green", "blue"); someFunc(1, "soap"); ?>
如果你比较狡黠,那么也许你会试着传递一个数组给函数someFunc(),然后发现它并没有显示数组元素而是简单的显示“Array”。你可以在函数内部通过对数组参数添加快速测试来修复这个问题,就像下列所重新编写的那样:
<?php // define a function function someFunc() { // get the number of arguments passed $numArgs = func_num_args(); // get the arguments $args = func_get_args(); // print the arguments print "You sent me the following arguments: "; for ($x = 0; $x < $numArgs; $x++) { print "<br />Argument $x: "; /* check if an array was passed and, if so, iterate and print contents */ if (is_array($args[$x])) { print " ARRAY "; foreach ($args[$x] as $index => $element) { print " $index => $element "; } } else { print " $args[$x] "; } } } // call a function with different arguments someFunc("red", "green", "blue", array(4,5), "yellow"); ?>