Trailing commas ถูกใช้ใน PHP ตั้งแต่เวอร์ชัน 7.2 เราสามารถใช้ trailing commas ในรายการสุดท้ายของอาร์เรย์ เราสามารถเพิ่มสมาชิกของอาร์เรย์ได้โดยไม่ต้องแก้ไขบรรทัดสุดท้ายของรายการ หากบรรทัดนั้นใช้ trailing comma อยู่แล้ว
Trailing Commas ก่อน PHP 8.0
ก่อน PHP 8 เราไม่สามารถเพิ่มคอมม่าท้ายพารามิเตอร์สุดท้ายได้
ตัวอย่าง
function($x,$y,$z){ }
ใน PHP 8.0
ใน PHP 8 เราสามารถเพิ่ม trailing commas ที่ท้ายพารามิเตอร์สุดท้ายได้ PHP 8 อนุญาตให้ใช้ trailing commas ในรายการพารามิเตอร์และ closure use list
ตัวอย่าง
function($x,$y,$z,){}
ตัวอย่าง: ใช้ Trailing Comma ใน PHP ในการเรียกฟังก์ชัน เมธอด และ closure
<?php
function EmployeeAdd(string $country, string $city, string $street): string {
return $country . ', ' . $city. ', ' . $street;
}
$result = employeeAdd(
'India',
'Bangalore',
'Indira Nagar',
);
print_r($result);
?>
ผลลัพธ์
India, Bangalore, Indira Nagar
ตัวอย่าง: Trailing Comma PHP 8 ด้วยอาร์กิวเมนต์หลายตัว
<?php
function method_with_many_arguments(
$x,
$y,
$z,
)
{
var_dump("shows valid syntax");
}
method_with_many_arguments(
1,
2,
3,
4,
);
?>
ผลลัพธ์
string(18) "shows valid syntax"