In PHP development, function parameters are very flexible. Two special parameters are particularly common: the variadic parameter ...$var and the callback parameter callable. They are used to handle an indefinite number of arguments and to pass executable callback logic into functions.
A variadic parameter allows a function to accept any number of arguments, which are automatically stored as an array. This is especially convenient when performing aggregation tasks such as summing values.
<?php function sum(...$numbers) { $total = 0; foreach ($numbers as $number) { $total += $number; } return $total; } echo sum(1, 2, 3, 4, 5); // Output: 15 ?>
In this example, the sum function uses the variadic parameter ...$numbers to accept multiple numbers and calculate their total.
The callable parameter type allows a function to receive another function as an argument, and execute it when needed. This is often used for filtering, sorting, or applying custom logic.
<?php function filterArray(array $array, callable $callback) { $filteredArray = []; foreach ($array as $element) { if ($callback($element)) { $filteredArray[] = $element; } } return $filteredArray; } $callback = function ($value) { return $value > 10; }; $filteredArray = filterArray([1, 2, 10, 15, 20], $callback); print_r($filteredArray); // Output: [15, 20] ?>
Here, the filterArray function takes an array and a callback function. The callback is used to check whether each element meets a condition, enabling flexible filtering logic.
By leveraging these two parameter types, PHP functions become more extensible and flexible, giving developers greater power and reusability in their code.