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);
Top comments (0)