dev-resources.site
for different kinds of informations.
PHP version 8.0 - Named Parameters
Published at
11/18/2024
Categories
webdev
php
codenewbie
laravel
Author
Hòa Nguyễn Coder
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: "[email protected]",
to: "[email protected]",
message: "This is a test email. Hòa Nguyễn Coder",
subject: "Hòa Nguyễn Coder",
isHtml: true);
Articles
12 articles in total
How to Connect Redis with PHP Using Docker Compose
read article
Factory Method Design Pattern Explained with PHP Examples
read article
Docker Compose Demo: Running Multiple Services with Two Domains on Localhost
read article
Set Up PHP 8 Environment Using Docker with a Custom Dockerfile
read article
PHP version 8.0 - Named Parameters
currently reading
Using ON DUPLICATE KEY UPDATE and NOT EXISTS in MySQL
read article
Mail Service using Singleton Design Pattern in PHP
read article
Sending Emails with Mailer in PHP + Symfony
read article
Fix Bug Search and Pagination in Vue.js: Dev Wants to Chill But Bug Doesn't Let
read article
Vue Tip : Setup Store Pinia + Custom Pagination
read article
⚡ MySecondApp - React Native with Expo (P24) - Animated Online Status for User
read article
⚡ MySecondApp - React Native with Expo (P23) - Layout My Account
read article
Featured ones: