Please wait

Named Arguments

Named arguments, also known as named parameters, were introduced in PHP 8.0. This feature allows you to specify the value of a function parameter by its name rather than its position in the function declaration. This can improve the readability and maintainability of your code, particularly for functions with a large number of parameters or optional parameters.

Using named arguments

Here's an example of how you might use named arguments:

function foobar(int $foo, float $baz = 1.0, string $bar = 'abc' ) {
  // Function body here
}
 
// Call function with named arguments
foobar(foo: 123, baz: 3.14, bar: "xyz");

In this example, we're calling the foobar function with three arguments: foo, baz, and bar. We're passing the values 123, 3.14, and "abc" respectively. The function will then use these values when it runs.

So why use them?

This feature can be especially useful when you have optional parameters. For instance, if you want to provide a value for bar but want to use the default value for baz, you can do so without having to pass a value for baz:

// Call function with named arguments, skipping 'bar'
foobar(foo: 123, bar: 3.14);

With named arguments, you can also pass arguments in any order:

// Call function with named arguments in different order
foobar(baz: 3.14, foo: 123, bar: "abc");

Please note that named parameters must be existing parameters in the function signature. If you pass a named parameter that is not defined in the function signature, PHP will throw a fatal error.

Key takeaways

  1. Named arguments, introduced in PHP 8.0, improve code readability by assigning values to function parameters by their names, not their order.
  2. They allow for skipping optional parameters and setting only those required, making the code more flexible and maintainable.
  3. The arguments can be passed in any order, but using non-existing parameter names in the function signature will result in a fatal error.

Comments

Please read this before commenting