DEV Community

Cover image for PHP version 8.0 - Named Parameters
Hòa Nguyễn Coder
Hòa Nguyễn Coder

Posted on

1

PHP version 8.0 - Named Parameters

Named Parameters in PHP 8

Now, in PHP 8, we can write functions using Named Parameters.

For example, suppose you have a function add($id, $title, $quantity). You can call it in the following ways:

add(id: 1, title: "Phone", quantity: 2);
add(title: "Phone", id: 2, quantity: 2);
Enter fullscreen mode Exit fullscreen mode

Named Parameters: This feature allows you to change the order of arguments when calling a function, as long as you specify the parameter names correctly in the function definition.


//Example 1: 
function createUser($name, $role = 'user', $isActive = true) {

    echo $name."-".$role;
}

createUser(name: 'Hòa Nguyễn', isActive: false, role:"admin");

//Example 2:
class CartService{

    public function add(int $id, string $title, bool $isActive = true) : string {
        return "$id, $title đã được thêm vào giỏ hàng";
    }
}

$cart = new CartService;
echo $cart->add(1, "Phone", true)."\n";
echo $cart->add(id: 2, isActive: true, title: "hoa")."\n";

//Example 3:
function sendEmail(string $from, string $to, string $subject, string $message,
 bool $isHtml = false) {
    echo "From: $from\n";
    echo "To: $to\n";
    echo "Subject: $subject\n";
    echo "Message: $message\n";
    echo "Is HTML: " . ($isHtml ? 'Yes' : 'No') . "\n";
}

//Gọi hàm với Named Arguments
sendEmail(
    from: "hoanguyen@example.com",
    to: "recipient@example.com", 
    message: "This is a test email. Hòa Nguyễn Coder", 
    subject: "Hòa Nguyễn Coder", 
    isHtml: true);

Enter fullscreen mode Exit fullscreen mode

PHP version 8.0 - Named Parameters

30 PHÚT DEV HỌC BUỔI TỐI | 🎧 Vừa chill vừa học lập trình

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →