PHP 8 interview question · Most asked
What are named arguments and what are their benefits and risks?
Summary
Named arguments let callers pass values by parameter name (fn(name: 'x')), so they can skip optional parameters and make call sites self-documenting.
Longer Answer
With named arguments the order no longer matters and you only pass what you need, which is ideal for functions with many optional flags like htmlspecialchars($s, double_encode: false). They can be combined with positional arguments, but positional ones must come first.
The risk: parameter names become part of your public API. Renaming a parameter in a library is now a breaking change for callers using named arguments. Child classes that rename parameters can also cause errors when the call goes through the parent signature. You can also spread string-keyed arrays: foo(...['b' => 2]).
Code Example
<?php
function createUser(string $email, bool $admin = false, bool $notify = true, ?string $locale = null) { /* ... */ }
// Before: createUser('[email protected]', false, false, 'de');
createUser('[email protected]', notify: false, locale: 'de');
echo htmlspecialchars('<a>&', double_encode: false);
Key Points
- Skip optional parameters without passing defaults
- Self-documenting call sites (
boolflags become readable) - Parameter names are now part of the public API
- Positional arguments must precede named ones; duplicates are an Error
Explanation
What interviewers look for
Mentioning the API-compatibility consequence for library authors, not just the convenience.
Common mistakes
- Placing a positional argument after a named one
- Renaming parameters in a minor library release
Follow-up questions
- How does
#[\SensitiveParameter]or deprecation tooling help with param renames?
More most-asked PHP 8 questions
- How should passwords be stored in PHP?
- What are the most important features introduced in PHP 8.0?
- What are union types in PHP 8 and how do you use them?
- What is constructor property promotion?
- How does `match` differ from `switch`?
- What happens to an HTTP request in a PHP-FPM application, and what does 'shared nothing' mean?
- What are enums in PHP 8.1? Explain pure vs backed enums.
- Explain readonly properties (8.1) and readonly classes (8.2).