Named arguments in PHP 8

Thu 23, Jul 2020 php webdev

Hi!

One of the coolest new features of PHP 8 are named arguments (parameters). I'm really happy that they made it into PHP 8, as they're a huge improvement syntax-wise, I think. But first, take a look at what they look like:

class Post {

    public function __construct(
        string $title,
        string $body,
        string $author
    ) {}

}

# ...

$post = new Post(
    title: 'Some interesting post',
    body: 'Bla bla body text here',
    author: 'John'
);

Why?

While this feature was highly debated, I think it comes with far more advantages than disadvantages. It allows for cleaner and easier to understand code (think (min: 0, max: 86400) instead of (0, 86400)). It also allows us to skip default values. Say we have the following function:

function cacheText(
    string $key,
    string $value,
    int $expires = 86400,
    string $directory = 'cache/'
) {}

If we now wanted to call this function with a different directory, but keep $expires with its default value, we can now write this

cacheText(
    key: 'content-home',
    value: 'something bla bla',
    directory: 'someOtherDir/'
);

instead of that:

cacheText(
    'content-home',
    'something bla bla',
    86400,
    'someOtherDir/'
);

Named arguments can also be used together with ordered arguments. That means that you could, for example, write this:

$post = new Post(
    'Some interesting post',
    body: 'Bla bla body text here',
    author: 'John'
);

What would not work, however, is doing it this way:

$post = new Post(
    title: 'Some interesting post',
    'Bla bla body text here',
    author: 'John'
);

You can only use ordered arguments together with named ones at the beginning of the argument list. If you're using ordered arguments between named ones, PHP throws an error.

Named arguments are also supported in annotations/attributes, by the way!

In case you want some more info on that, view this article and the RFC!


Back to top