PHP 8: Modern PHP Development · Modern PHP Syntax & Types
Named Arguments, Defaults and Spread
Call functions by parameter name, skip defaults, and unpack arrays into arguments.
Named arguments (8.0) let you pass values by parameter name, in any order, and skip optional parameters. They make calls with many booleans or options self-documenting. The spread operator ... unpacks arrays (including string keys, since 8.1) into arguments and collects variadic parameters.
<?php
// Self-documenting calls
$json = json_encode($data, flags: JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$html = htmlspecialchars($input, double_encode: false);
function createUser(string $email, string $role = 'member', bool $active = true): User { /* ... */ }
createUser('[email protected]', active: false); // skip $role
// Spread with string keys maps to named arguments (8.1+)
$args = ['email' => '[email protected]', 'role' => 'admin'];
createUser(...$args);
function sum(int ...$numbers): int { return array_sum($numbers); }
echo sum(1, 2, 3); // 6
Common pitfalls
- Parameter names become part of your public API — renaming a parameter can break callers using named arguments.
- Mixing positional arguments after named ones is a compile error.
- Passing an unknown named argument throws an
Error.
Key points
- Named arguments make boolean/options calls readable
- Parameter names are now part of the API contract
- Spread unpacks arrays; string keys map to names
Further reading: PHP manual: named arguments
Practice questions
Why are parameter renames a breaking change since PHP 8?
Answer
Callers may pass arguments by name (foo(limit: 10)), so renaming $limit to $max causes an Error: Unknown named parameter. Library authors should treat parameter names as public API.
How do you skip one optional parameter but set a later one?
Answer
Use a named argument for the later parameter: createUser('[email protected]', active: false) keeps the default for $role. Before PHP 8 you had to repeat the default value positionally.
Open in the app to mark lessons complete, take notes and track your progress.