Home >Backend Development >PHP Tutorial >PHP version - Named Parameters

PHP version - Named Parameters

Patricia Arquette
Patricia ArquetteOriginal
2024-11-20 01:04:03315browse

PHP version  - 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);

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);

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

The above is the detailed content of PHP version - Named Parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn