Prior to PHP 8, devs used to struggle sometimes with some helpers or built-in utilities, as the only way to pass inputs correctly was to write them in the exact same order as defined by the method signature.
Forget the current order
You can now use the name of the arguments instead, and it works with objects and classes too:
class Post
{
public function __construct(
public string $title,
public string $desc,
) {}
}
$post = new Post(
desc: "My desc",
title: "My title",
);
Don't mix the syntaxes
Don't use both positional and named arguments in your calls, as it's prone to errors.
PHP won't understand what you're trying to achieve if your named argument comes before a positional argument.
Note that, theoretically, you can mix both as long as you put named arguments after positional arguments, but, still, I would not recommend such usage.
The benefits in short
- the code is more readable, as, unlike positions, names are meaningful
- methods are "self-documented"
- you can skip default arguments
- named arguments are pretty helpful in annotations and attributes too
- no more confusion between the haystack and the needle
N.B.: the last point is a private joke, as many built-in PHP utilities use similar names but in different order (legacy code)
The big caveat
Named arguments are pretty cool in my experience. The only caveat is that it could encourage a bad practice that consists of creating unnecessary long helpers, with sometimes more than 8 parameters!
Even if named arguments can ease the pain with such "monsters," I would still recommend splitting them into several helpers with less parameters.
Too much parameters usually indicates the helpers handles too much tasks.
Top comments (2)
Hey, I really agree. Named arguments are a great feature but having so many arguments in a method could be a bad smell alarm
Absolutely!
It's a give-and-take. I'm glad they add this feature, though. When correctly used, it really improves readability.