PHP 8: The joy of named arguments

spO0q 🐒 - May 14 '23 - - Dev Community

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",
);
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player