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>&amp;', double_encode: false);

Key Points

  • Skip optional parameters without passing defaults
  • Self-documenting call sites (bool flags 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

← All PHP 8 questions