How do I write a function that can accept unlimited number of parameters?
What am trying to do is create a function within a class that wraps the following:
If you are using PHP 5.6 or later version, argument lists may include the ...
token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; Simply Using ...
you can access unlimited variable arguments.
for example:
<?php
function sum(...$numbers) {
$sum = 0;
foreach ($numbers as $n) {
$sum += $n;
}
return $sum ;
}
echo sum(1, 2, 3, 4, 5);
?>
If you are using PHP version <= 5.5 then you can access unlimited parameterusing the func_num_args(), func_get_arg(), and func_get_args() functions.
For example:
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs \n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}
foo(1, 2, 3);
?>
There is a function called func_get_args() which is an array of all arguments passed to the function.
Example from PHP.net
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
The above example will output:
Number of arguments: 3
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3