PHP 8.0: Trailing commas are allowed in parameter lists and closure use lists

Version8.0
TypeChange

PHP 8.0 syntax allows to leave a trailing-comma in parameter lists and closure use lists.

function foo(string $foo, string $bar,) {}

function() use ($foo, $bar,) {

}

PHP 7.2 eased the syntax to allow trailing commas in grouped use statements for grouped use statements; PHP 7.3 eased the syntax to allow trailing commas in function and method calls, and this change in PHP 8.0 allows trialing commas in function/method declarations and use lists in closures.

class Request {
    public function __construct(  
        $method,  
        UriInterface $uri,  
        HeadersInterface $headers,  
        array $cookies,  
        array $serverParams,  
        StreamInterface $body,  
        array $uploadedFiles = [],  
    ) {
        // ...
    }
}

Prior to PHP 8.0, this would have caused a parse error due to the disallowed trailing comma in the parameter list, at array $uploadedFiles = [],:

Parse error: syntax error, unexpected ')', expecting variable (T_VARIABLE) in ... on line ...

Similarly, trailing commas are allowed in PHP 8.0, but resulted in a parse error in earlier versions:

function() use (
        $foo, 
        $bar,
    ) {

}
Parse error: syntax error, unexpected ')', expecting '&' or variable (T_VARIABLE) in ... on line ...

One of the major benefits of this is that diff outputs will be cleaner when new parameters or use variables are appended.

In the snippets above, adding a new parameter or a use variable to the end would produce simpler diff outputs, because the line with last parameter is not modified.

        StreamInterface $body,  
        array $uploadedFiles = [], 
+       array $extraOptions = [],
     )

Without the trailing-commas allowed, the diff output would include the changes in the last line as well:

        StreamInterface $body,
-       array $uploadedFiles = []
+       array $uploadedFiles = [], 
+       array $extraOptions = []
     )

Backwards Compatibility Impact

Due to this being a syntax change, this feature cannot be back-ported.

All code that contains trailing commas in parameter lists, or closure use lists will produce parse errors in versions prior to PHP 8.0:

Using trailing commas in parameter lists in PHP < 8.0

Parse error: syntax error, unexpected ')', expecting variable (T_VARIABLE) in ... on line ...

Using trailing commas in closure use lists in PHP < 8.0

Parse error: syntax error, unexpected ')', expecting '&' or variable (T_VARIABLE) in ... on line ...

Parameter lists

RFC Implementation

Closure use lists RFC Implementation