4.15.6 Variable parameter counts: func_num_args(), func_get_arg(), and func_get_args()This is NOT the latest copy of this book; click here for the latest version.
int func_num_args ( )
mixed func_get_arg ( int arg_num)
array func_get_args ( )
The printf() function we examined previously is able to take an arbitrary number of parameters. That is, it could take just one parameter, or five, or fifty, or five hundred - it can take as many as are passed into it by the user. This is known as a variable-length parameter list, and it is automatically implemented in your user functions. For example:
<?php
function some_func($a, $b) {
$j = 1;
}
some_func(1,2,3,4,5,6,7,8); ?>
Here the function some_func() is defined to only take two parameters, $a and $b, but we call it with eight parameters and the script should run without a problem. In that example, 1 will be placed into $a, and 2 will be placed into $b, but what happens to the other parameters?
Coming to your rescue are three functions: func_num_args(), func_get_arg(), and func_get_args(), of which the first and last take no parameters. To get the number of arguments that were passed into your function, call func_num_args() and read its return value. To get the value of an individual parameter, use func_get_arg() and pass in the parameter number you want to retrieve to have its value returned back to you. Finally, func_get_args() returns an array of the parameters that were passed in. Here's an example:
<?php
function some_func($a, $b) {
for ($i = 0; $i < func_num_args(); ++$i) {
$param = func_get_arg($i);
echo "Received parameter $param.\n";
}
}
function some_other_func($a, $b) {
$param = func_get_args();
$param = join(", ", $param);
echo "Received parameters: $param.\n";
}
some_func(1,2,3,4,5,6,7,8);
some_other_func(1,2,3,4,5,6,7,8); ?>
Using func_num_args() alone you can easily implement function error checking. You can, for example, start off each of your functions by checking to make sure func_num_args() is what you are expecting, and, if not, exit. Once you add func_get_arg() into the mix, however, you should easily be able to create your own functions that work with any number of parameters.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|