Normally you pass arguments in the same order as the parameters. With named arguments, you write the parameter name, so the order does not matter. They arrived in PHP 8.0.
<?php
function createButton(string $label, string $color = "blue", bool $disabled = false): string
{
return "$label ($color)" . ($disabled ? " [disabled]" : "");
}
echo createButton(label: "Save", disabled: true);
Save (blue) [disabled]
We skipped $color and still set $disabled. With positional arguments, you would have to write createButton("Save", "blue", true) and repeat the default.
Order does not matter
<?php
function range3(int $start, int $end, int $step = 1): string
{
return implode(",", range($start, $end, $step));
}
echo range3(end: 10, start: 0, step: 5);
0,5,10
Clearer calls
Compare these two calls. The second is understandable without opening the function.
setcookie("theme", "dark", 0, "/", "", true, true);
setcookie(
name: "theme",
value: "dark",
expires_or_options: 0,
path: "/",
secure: true,
httponly: true,
);
Named arguments are most useful for boolean flags and for functions with many optional parameters.
With built-in functions
<?php
echo str_pad(string: "7", length: 3, pad_string: "0", pad_type: STR_PAD_LEFT) . "\n";
echo json_encode(value: ["a" => 1], flags: JSON_PRETTY_PRINT);
007
{
"a": 1
}
Rules
- Positional arguments must come before named ones.
- You cannot pass the same parameter twice.
- A name that does not exist is an error.
<?php
function area(int $width, int $height): int
{
return $width * $height;
}
echo area(5, height: 3) . "\n"; // positional first, then named
try {
echo area(width: 5, depth: 3);
} catch (Error $e) {
echo $e->getMessage();
}
15
Unknown named parameter $depth
A warning for library authors
Parameter names are now part of a function’s public interface. If you rename a parameter in a library, you break callers who use the old name.