In the course of converting some code from Java to PHP, I came across the following Java code:
void doSomething(String requiered, String... optionals) {...}
I know it's possible to create a similar function signature using func_get_args()
and I know I could also pass the unknown count of params in an array. However, neither seems straight forward to me, so I was wondering if there might be a better way to have a variable number of arguments in PHP.
PHP 5.6 introduces ability to have this exact construct. From PHP manual:
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
<?php
function sum($acc, ...$numbers) {
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
echo sum(1, 2, 3, 4);
?>
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list