Named Arguments
What Are Named Arguments? In simple terms: Named arguments let you pass values to a function by writing the parameter name next to each value, instead of relying only on the order of the values. Techn
What Are Named Arguments?
In simple terms: Named arguments let you pass values to a function by writing the parameter name next to each value, instead of relying only on the order of the values.
Technically: Introduced in PHP 8.0, named arguments use the syntax parameterName: value in a function call. PHP matches each named argument to the parameter with that name, so the order of named arguments does not matter, and optional parameters in between can be skipped.
// Positional: what do 0 and false mean?
formatAmount(1234.5, 0, '₹', false);
// Named: self-explanatory
formatAmount(1234.5, decimals: 0, showSymbol: false);
Why Named Arguments Were Added
- Readability: calls such as
f(true, false, null, 3)give no hint about what each value means. - Skipping optional parameters: without named arguments, changing the last optional parameter required repeating the defaults of every parameter before it.
- Order independence: you cannot accidentally swap two values of the same type.
Syntax
functionName(parameterName: value, otherParameter: value);
- The name is written without the
$. - A colon separates the name and the value.
- Named arguments can be combined with positional arguments, but positional ones must come first.
Example
<?php
function createUser(
string $name,
string $role = 'viewer',
bool $active = true,
?string $team = null,
): string {
return sprintf(
'%s | role: %s | active: %s | team: %s',
$name,
$role,
$active ? 'yes' : 'no',
$team ?? 'none',
);
}
echo createUser('Asha', team: 'Sales') . "\n";
echo createUser(name: 'Bala', active: false) . "\n";
echo createUser(team: 'Support', name: 'Charu', role: 'editor') . "\n";
Output
Asha | role: viewer | active: yes | team: Sales
Bala | role: viewer | active: no | team: none
Charu | role: editor | active: yes | team: Support
How Each Call Works
createUser('Asha', team: 'Sales')—'Asha'is positional (first parameter).teamis set by name.roleandactivekeep their defaults, even though they come beforeteamin the declaration.createUser(name: 'Bala', active: false)— all arguments are named;roleandteamuse defaults.createUser(team: 'Support', name: 'Charu', role: 'editor')— named arguments in any order.
Without named arguments, the first call would have to be written as createUser('Asha', 'viewer', true, 'Sales'), repeating two defaults just to reach $team.
Named Arguments With Built-in Functions
Named arguments work with built-in functions too, using the parameter names shown in the PHP manual.
<?php
echo str_pad('7', 3, '0', STR_PAD_LEFT) . "\n";
echo str_pad(string: '7', length: 3, pad_string: '0', pad_type: STR_PAD_LEFT) . "\n";
echo htmlspecialchars('& <b>', double_encode: false) . "\n";
echo json_encode(['city' => 'சென்னை'], flags: JSON_UNESCAPED_UNICODE) . "\n";
var_dump(in_array(needle: '5', haystack: [5], strict: true));
echo implode(', ', array_fill(start_index: 0, count: 3, value: 'x')) . "\n";
Output
007
007
& <b>
{"city":"சென்னை"}
bool(false)
x, x, x
Why This Helps
htmlspecialchars(..., double_encode: false)— thedouble_encodeparameter is the fourth parameter. Without named arguments, you would need to pass the default flags and encoding first:htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false).in_array(..., strict: true)— makes it obvious that thetruemeans strict comparison.array_fill(start_index: ..., count: ..., value: ...)— prevents mixing up two integer arguments.
The names of built-in parameters are listed in each function's signature in the manual (for example, str_pad(string $string, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT)).
Rules and Errors
Positional Arguments Must Come First
createUser(name: 'Asha', 'editor');
Result: Fatal error at compile time: Cannot use positional argument after named argument. Once you start naming arguments, every following argument must also be named.
Unknown Parameter Names
<?php
function createUser(string $name, string $role = 'viewer'): string
{
return "$name ($role)";
}
try {
echo createUser('Asha', email: 'asha@example.com');
} catch (Error $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
Error: Unknown named parameter $email
PHP checks names when the call happens. A typo in a parameter name causes an error instead of being silently ignored.
Setting the Same Parameter Twice
<?php
function createUser(string $name, string $role = 'viewer'): string
{
return "$name ($role)";
}
try {
echo createUser('Asha', name: 'Bala');
} catch (Error $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
Error: Named parameter $name overwrites previous argument
'Asha' was already assigned positionally to $name, so naming $name again is an error.
Required Parameters Are Still Required
createUser(role: 'editor'); // ArgumentCountError: $name was not passed
Named arguments only change how values are matched; every required parameter must still receive a value.
Unpacking Arrays Into Named Arguments (PHP 8.1+)
When an array with string keys is unpacked with ..., the keys are used as parameter names:
<?php
function createUser(
string $name,
string $role = 'viewer',
bool $active = true,
?string $team = null,
): string {
return sprintf('%s | role: %s | active: %s | team: %s', $name, $role, $active ? 'yes' : 'no', $team ?? 'none');
}
$formData = ['name' => 'Dev', 'role' => 'admin'];
echo createUser(...$formData) . "\n";
Output
Dev | role: admin | active: yes | team: none
This is convenient when arguments are prepared as an associative array, such as configuration values. Make sure the keys come from your own code, not directly from user input: unexpected keys cause "Unknown named parameter" errors.
Collecting Extra Named Arguments With Variadics
A variadic parameter (...$name) collects extra named arguments into an array with string keys:
<?php
function htmlTag(string $tag, string $content, string ...$attributes): string
{
$html = '';
foreach ($attributes as $attribute => $value) {
$html .= sprintf(' %s="%s"', $attribute, htmlspecialchars($value));
}
return "<$tag$html>" . htmlspecialchars($content) . "</$tag>";
}
echo htmlTag('a', 'View course', href: '/courses/php', class: 'btn') . "\n";
Output
<a href="/courses/php" class="btn">View course</a>
href and class are not declared parameters, so they are collected in $attributes as ['href' => '/courses/php', 'class' => 'btn']. Variadic functions are covered in Variadic Functions.
Parameter Names Become Part of the API
With named arguments, callers depend on your parameter names, not only on their order. Renaming a parameter — for example, from $team to $department — breaks every call that uses team:.
Practical consequences:
- Choose clear parameter names from the start.
- Treat renaming a parameter of a public function as a breaking change, just like removing it.
- In libraries, document whether named arguments are supported for a function.
When to Use Named Arguments
| Situation | Recommendation |
|---|---|
The function has one or two obvious parameters (strlen($s), max($a, $b)) | Positional |
Boolean or null arguments whose meaning is unclear | Named |
| You want to set an optional parameter far down the list | Named |
| Several parameters of the same type that could be swapped | Named |
| Constructors with many optional settings | Named |
Common Mistakes
Positional Argument After a Named One
Effect: Fatal compile error.
Fix: Put all positional arguments first.
Typos in Parameter Names
Effect: Error: Unknown named parameter.
Fix: Check the function signature; editors autocomplete parameter names.
Using $ in the Name
createUser('Asha', $team: 'Sales'); // parse error
Fix: Write the name without $: team: 'Sales'.
Unpacking User-Controlled Arrays
Effect: Unexpected keys cause errors, and callers can set parameters you did not intend to expose.
Fix: Build the argument array from validated, known keys.
Renaming Parameters Without Considering Callers
Effect: Existing named calls break.
Fix: Treat parameter names as part of a function's public contract.
Best Practices
- Use named arguments to clarify boolean,
null, and same-typed arguments. - Use them to skip optional parameters instead of repeating default values.
- Keep positional arguments first, followed by named ones.
- Choose stable, descriptive parameter names, since callers depend on them.
- Use positional arguments for short, obvious calls; named arguments are a readability tool, not a requirement.
Official reference: https://www.php.net/manual/en/functions.arguments.php#functions.named-arguments