Functions with unknown amount of variables
This feature is very powerful, but not all programmers use it.
OK, so, the trick: we can declare function with some amount of parameters and call it with more parameters then declared. (But not less - this will cause an error).
How to manage this stuff in function?
firstly, let's review three main functions:
func_num_args()
int func_num_args ( void )
Gets the number of arguments passed to the function.
This function may be used in conjunction with func_get_arg() and func_get_args() to allow user-defined functions to accept variable-length argument lists.
func_get_arg()
mixed func_get_arg ( int $arg_num )
Gets the specified argument from a user-defined function's argument list.
func_get_args()
array func_get_args ( void )
Gets an array of the function's argument list.
OK, very good. Seems like understood.
Where it may be useful?
For specific functions which may be performed on any amount of similar data, like, for example, minimum or maximum.
Function will look like following:
$args = func_num_args();
if ($args == 0){
echo 'function average() must recieve at least one argument!';
return NULL;
}
else{
$params = func_get_args();
return array_sum($params)/count($params);
}
}
and then use it like
etc.
I saw several time when someone writes something like
foreach($arg_arr as $param){
//something here
}
}
and then calles the function like
and I think this may be made more nice, tricky and hacky when you know about this things with functions agruments.