Today I’d like to talk about a cool feature introduced in PHP 8: named parameters. When I first read about this feature, I was like “Okay, cool, but why?” But after a bit of experimentation, I’ve come to see just how powerful they can be. So let’s dive into the magical world of named parameters, shall we?

The Old Ways

Before PHP 8, we called functions with parameters by respecting the order set in the function declaration. I bet you’ve written something like this a thousand times:

function makeCoffee(string $type = 'drip', string $milk = 'whole', int $sugar = 1){
    // code here...
makeCoffee('drip', 'almond', 2);

It’s clear, concise, and gets the job done. But let’s be honest, it’s also kind of rigid. If I want a regular drip coffee with whole milk and no sugar, I need to pass all preceding parameters, which can be a bit of a headache:

makeCoffee('drip', 'whole', 0);

A New Dawn with Named Parameters

Enter PHP 8 and its named parameters. Now you can forget about the order of arguments. Instead, pass in parameters in any order, just by specifying their names. Check it out:

makeCoffee(milk: 'almond', sugar: 2);

Notice something missing? Yep, we didn’t include the type parameter at all, and it didn’t break a thing. Neat, right? Now, lets go back to when we wanted a regular drip coffee with whole milk and no sugar. You guessed it:

makeCoffee(sugar: 0);

When Things Get Tricky

Now, before you get too excited and start rewriting all your functions, there’s something you should know. If you have required parameters, you must provide them when calling the function. Otherwise, you’ll face a good ol’ fatal error.

Let’s say you have a function that has a required parameter and some optional ones, like so:

function brewCoffee(string $type, int $temperature = 195){
    // code here...

If you use named parameters and leave out type, you’re gonna have a bad time:

brewCoffee(temperature: 205); // Throws a fatal error

But if you include the type, everything’s hunky-dory:

brewCoffee(temperature: 205, type: 'columbian'); // Works perfectly

Wrapping Up

So there you have it, folks! Named parameters in PHP 8. A simple, yet revolutionary concept that can bring flexibility and readability to your codebase. It’s like PHP just handed us a shiny new tool for our coding toolbox. And as with any tool, it’s up to us to decide when and how to use it best.

So go out there and start experimenting with named parameters. Try them out in different scenarios and see how they can help you.