Default Argument Values
Give arguments a fallback value used when none is supplied.
Syntax
function name($arg = defaultValue) { ... }You can assign a default value to an argument. If the caller does not provide that argument, the default is used.
Arguments with defaults should come after arguments without defaults.
PHP 8 also supports named arguments, letting you pass values by name in any order.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Give a pagination function a default $perPage of 20 so callers can omit it for standard listings.
- Default a $format argument to 'json' in an API response helper so most callers don't need to specify it.
- Set a default $separator of ', ' in an array-join utility so it works sensibly without arguments.
More examples
Simple default argument
Default values are used when the caller omits that argument; required parameters must come before optional ones.
<?php
function paginate(int $page = 1, int $perPage = 20): array {
$offset = ($page - 1) * $perPage;
return ['offset' => $offset, 'limit' => $perPage];
}
print_r(paginate()); // offset:0, limit:20
print_r(paginate(3, 10)); // offset:20, limit:10Default null for optional objects
Defaulting a parameter to null signals it is optional; ?? inside the function provides a usable fallback.
<?php
function render(string $template, ?array $data = null): string {
$data ??= [];
ob_start();
extract($data);
include $template;
return ob_get_clean();
}Default array and string values
Scalar defaults give a sensible out-of-the-box experience while letting callers override any combination.
<?php
function listItems(array $items, string $sep = ', ', string $wrapper = ''): string {
$joined = implode($sep, $items);
return $wrapper ? "$wrapper$joined$wrapper" : $joined;
}
echo listItems(['a', 'b', 'c']); // a, b, c
echo listItems(['a', 'b', 'c'], ' | ', '*'); // *a | b | c*
Discussion