0
0
PhpConceptBeginner · 3 min read

Named Argument in PHP: What It Is and How to Use It

A named argument in PHP lets you pass values to a function by specifying the parameter name instead of just the order. This makes your code easier to read and allows skipping optional parameters. Named arguments were introduced in PHP 8.0.
⚙️

How It Works

Imagine you are ordering a pizza by phone. Instead of listing toppings in a fixed order, you say exactly what you want, like "extra cheese" and "no olives." Named arguments in PHP work similarly. When calling a function, you specify the name of the parameter along with its value, so the function knows exactly which argument you mean.

This means you don't have to remember the exact order of parameters. You can also skip some optional ones if you want. Behind the scenes, PHP matches the names you provide with the function's parameters and assigns the values accordingly.

💻

Example

This example shows a function with three parameters. We call it using named arguments to specify only the ones we want, in any order.

php
<?php
function createUser(string $name, int $age, string $city = "Unknown") {
    echo "Name: $name, Age: $age, City: $city";
}

// Using named arguments
createUser(age: 25, name: "Alice");
?>
Output
Name: Alice, Age: 25, City: Unknown
🎯

When to Use

Use named arguments when you want to make your function calls clearer and easier to understand, especially if the function has many parameters. They are helpful when some parameters are optional and you want to skip some without passing all previous ones.

For example, in a settings function with many options, named arguments let you change only what you need without confusion. They also reduce errors caused by mixing up the order of arguments.

Key Points

  • Named arguments let you specify parameter names when calling functions.
  • They improve code readability and flexibility.
  • Introduced in PHP 8.0.
  • You can skip optional parameters by naming only the ones you want.
  • Order of arguments does not matter when using named arguments.

Key Takeaways

Named arguments allow passing values by parameter name, not just position.
They make function calls clearer and reduce mistakes with argument order.
You can skip optional parameters easily using named arguments.
Named arguments require PHP 8.0 or newer.
Use named arguments to improve code readability and maintainability.