Trailing Commas in Parameter List and Closure use List in PHP 8.0

PHP allows to use a trailing comma for the last item in the array. It’s for convenience because we can add another element to the array without modifying the last line of the item if that line already uses a trailing comma.

<?php

$array = [
    'First',
    'Seoond',
    'Third',
];

Since PHP 7.2 we can use a trailing comma in grouped namespace.

<?php

use App\Service\{
    Sender,
    Builder,
    Generator,
};

Since PHP 7.3 we can use a trailing comma in function, method and closure calls.

<?php

function formatAddress(string $country, string $city, string $street): string {
    return $street . ', ' . $city . ', ' . $country;
}

$result = formatAddress(
    'USA',
    'San Francisco',
    'Valley St',
);

Since PHP 8.0 we can use a trailing comma in function, method and closure parameter lists.

<?php

function formatAddress(
    string $country,
    string $city,
    string $street,
): string {
    return $street . ', ' . $city . ', ' . $country;
}

Since PHP 8.0 we can use a trailing comma in closure use list.

<?php

$country = 'USA';
$city = 'San Francisco';
$street = 'Valley St';

$getFormatedAddress = function() use (
    $country,
    $city,
    $street,
) {
    return $street . ', ' . $city . ', ' . $country;
};

Leave a Comment

Your email address will not be published. Required fields are marked *