Sử dụng Match expression trong PHP 8. Giúp đoạn code của ta trông maintain hơn.
$statusCode = 200;
$result_v1 = match ($statusCode) {
200, 300 => "Thành công",
400 => "Lỗi client",
500 => "Lỗi server",
default => "Không xác định",
};
$result_v2 = match ($statusCode) {
200, 300 => function($statusCode) {
return "Thành công!".$statusCode;
},
400 => function() {
return "Lỗi client";
},
500 => "Lỗi server",
default => "Không xác định",
};
// Gọi hàm nếu kết quả là một closure
echo is_callable($result_v2) ? $result_v2($statusCode) : $result_v2;
Ví dụ chúng ta tính toán giá khuyến mãi
function calculateDiscount($price, $percentage) : float {
return $price * (1 - $percentage / 100);
}
$customerType = "gold";
$originalPrice = 1000;
$discountedPrice = match ($customerType) {
"bronze" => fn($price) => calculateDiscount($price, 5),
"silver" => fn($price) => calculateDiscount($price, 10),
"gold" => fn($price) => calculateDiscount($price, 15),
"platinum" => fn($price) => calculateDiscount($price, 20),
default => fn($price) => $price, // Không giảm giá
};
// Áp dụng giảm giá và làm tròn đến 2 chữ số thập phân
$finalPrice = round($discountedPrice($originalPrice), 2);
echo "Loại khách hàng: $customerType\n";
echo "Giá gốc: $originalPrice\n";
echo "Giá sau khuyến mãi: $finalPrice\n";
// Tính phần trăm giảm giá
$discountPercentage = (($originalPrice - $finalPrice) / $originalPrice) * 100;
echo "Phần trăm giảm giá: " . round($discountPercentage, 2) . "%\n";