Named arguments are a feature introduced in PHP 8 that allows developers to pass arguments to functions or methods by specifying their names explicitly, instead of relying on their position. This makes it easier to understand the code and prevents errors that may occur when the order of the arguments changes.

Named arguments example:

function send_email($to, $subject, $message, $from = 'noreply@example.com') {
    echo "To: $to
";
    echo "Subject: $subject
";
    echo "Message: $message
";
    echo "From: $from
";
}

// Call the function using named arguments
send_email(
    to: 'johndoe@example.com',
    subject: 'Test Email',
    message: 'This is a test email.',
    from: 'info@example.com'
);

 

In what scenarios named arguments are useful?

Consider you have a function like this, where it gets four parameters and using those variables it compiles a message and returns the value.  $footer  and  $title  are optional parameters in this function. But if you want to skip one of the optional parameters, for example,  $footer , then you can't do it straight away. You have to pass empty param and that solution looks ugly, checkout below example.

function compile($header, $message, $footer = '', $title = ''){ ... }
While calling the above function, we must provide value for $footer at least we need to call like this:
compile($header,$message, , $title);
This is the one scenario where the named arguments are useful. You can simply call like shown below and it works well and also it is readable. 
compile($header, $message, title:$title)

 


Comments (0)
Leave a Comment

loader Posting your comment...