0
0
PHPprogramming~5 mins

Named arguments in PHP

Choose your learning style9 modes available
Introduction

Named arguments let you give values to function parameters by name. This makes your code easier to read and understand.

When a function has many parameters and you want to specify only some of them.
When you want to make your code clearer by showing which value goes to which parameter.
When you want to change the order of parameters without confusion.
When you want to skip optional parameters and only set the ones you need.
Syntax
PHP
functionName(parameterName: value, anotherParameter: value);

You write the parameter name, then a colon, then the value.

You can mix named arguments with regular positional arguments, but positional ones must come first.

Examples
Call the function using named arguments in the same order as parameters.
PHP
<?php
function greet(string $name, string $greeting) {
    echo "$greeting, $name!";
}
greet(name: "Alice", greeting: "Hello");
Call the function with named arguments in a different order.
PHP
<?php
function greet(string $name, string $greeting) {
    echo "$greeting, $name!";
}
greet(greeting: "Hi", name: "Bob");
Use named argument to skip the optional parameter and use its default value.
PHP
<?php
function setUser(string $name, int $age = 30) {
    echo "$name is $age years old.";
}
setUser(name: "Carol");
Sample Program

This program shows how to call a function with named arguments in any order and how to skip optional parameters.

PHP
<?php
function bookInfo(string $title, string $author, int $year = 2020) {
    echo "Title: $title\nAuthor: $author\nYear: $year\n";
}

// Using named arguments in any order
bookInfo(author: "Jane Austen", title: "Pride and Prejudice", year: 1813);

// Skipping optional argument
bookInfo(title: "1984", author: "George Orwell");
OutputSuccess
Important Notes

Named arguments were introduced in PHP 8.0.

Positional arguments must come before named arguments in a function call.

Using named arguments improves code readability, especially with many parameters.

Summary

Named arguments let you specify function parameters by name.

You can change the order of arguments when calling functions.

They help skip optional parameters and make code easier to read.