Default and Named Arguments
September 28, 2021
PHP 8 allows us to specify default arguments to pass to our function.
PHP allows us to specify default arguments to pass to our function argument list within parenthesis. In the example below I'm passing $type of type string, $cost of type float, and $temperature of type string to my beverage function.
function beverage(string $type = '', float $cost = 0, string $temperature = '')
{
$served = (in_array($temperature, ['hot', 'cold', 'warm'])) ? $temperature : 'warm';
return 'Your ' . $type . ' beverage will cost ' . $cost . ' and will be served ' . $served;
}
$drink = beverage('Coffee', 4.95, 'hot');
print ($drink);
But what if the caller forgets to set the $type variable, and instead does the following:
$drink = beverage(4.99, 'hot'); // Missing argument 1 - drink type!!
print ($drink);
Prior to PHP 8 this situation would throw a type mismatch error because the order of arguments doesn't match what the fuction, beverage, is expecting. The incoming values cost ("4.99") and temperature ("hot") are pased to the $type and $cost field respectively. PHP 8 addresses this issue by providing named arguments which allows the caller to specify which values are assigned to what argument in the functions argument list:
$drink = beverage(
cost: 5.67,
temperature: 'hot'
);
print ($drink);
Even though the first argument the function beverage is expecting ($type) is not specified by the caller, because we're using name:value pairs in the parameter list being sent to beverage, PHP 8 will know what value is assigned to what argument.