How does PHP handle function calls with varying numbers of arguments?
PHP allows for functions to have a varying number of arguments by using the special variable func_get_args() within the function definition. This variable captures all the arguments passed to the function in an array, which can then be looped through or accessed directly as needed. This allows for flexibility in function calls without having to define multiple function signatures.
function sum() {
$args = func_get_args();
$total = 0;
foreach ($args as $arg) {
$total += $arg;
}
return $total;
}
echo sum(1, 2, 3); // Output: 6
echo sum(4, 5, 6, 7); // Output: 22