Variadic functions
Collect ...
Three dots before the last parameter collect the rest into one array. The function then accepts zero or more values in that slot.
Name the packed array in plural so calls read well and loops stay clear.
function sumAll(int ...$nums): int {
return array_sum($nums);
}
echo sumAll(1, 2, 3);
echo sumAll();
Spread calls
Three dots also unpack an array into separate arguments at call time. One packed list can feed any function that expects single values.
Use spread to forward arrays into helpers without writing long argument lists by hand.
$list = [4, 5, 6];
// sumAll from above
echo sumAll(...$list);
Mixed fixed+variadic
Fixed parameters come first and the packed part comes last. Callers always pass the fixed values, then add as many extras as needed.
This shape suits loggers where level stays required while message parts vary.
function logMsg(string $level, string ...$parts): string {
return $level . ": " . implode(" ", $parts);
}
echo logMsg("info", "cache", "warm");
func_get_args legacy note
Older code reads extra arguments with func_get_args and friends. It works but hides the signature from readers and tools.
Prefer real variadics in new code and keep the legacy helpers only when patching old functions.
function legacySum(): int {
return array_sum(func_get_args());
}
echo legacySum(1, 2, 3);
Next: References
Автор статьи: Arthur Isaev