patternphplaravelTip
PHP 8.0 Named Arguments for Readable Function Calls
Viewed 0 times
PHP 8.0+
named argumentsnamed parametersphp 8.0readabilityarray_slicefunction call
Error Messages
Problem
Functions with many optional parameters require passing nulls or false as positional placeholders to reach the parameter you actually want to change, making call sites unreadable and error-prone.
Solution
Use named arguments to pass only the parameters you need, in any order: array_slice(array: $items, offset: 2, preserve_keys: true). Skip optional parameters entirely. This is especially useful for built-in PHP functions with many boolean flags.
Why
Named arguments improve readability, self-document intent, and prevent positional mismatches. They also future-proof code against parameter additions in a library.
Gotchas
- Named arguments must come after positional arguments in a call
- Named arguments use the parameter name as declared in the function signature—renaming parameters is a breaking change
- Cannot use named arguments with variadic (...$args) parameters beyond the variadic position
- Named arguments work with constructors, closures, and built-in functions
Code Snippets
Named arguments skipping optional parameters
// Before: confusing positional call
$result = array_slice($items, 2, null, true);
// After: self-documenting
$result = array_slice(array: $items, offset: 2, preserve_keys: true);
// With custom functions
function createUser(string $name, string $role = 'viewer', bool $active = true): User {}
createUser(name: 'Alice', active: false);Revisions (0)
No revisions yet.