With the new minor version upgrade PHP 7.3, trailing commas are introduced for function calls. A few thoughts why this is a good thing but does not go far enough.
What are trailing commas? Let’s see a simple example of PHP’s array syntax:
<?php $colors = [ 'blue', 'red', 'green', ];
We separated individual elements with a comma but we also used a comma after the last element (‘green’). This comma isn’t syntactically necessary, but I’d argue it is a better coding practice to put it there. First, when a new element should be added (let’s say, yellow), we do not have to add a comma after ‘green’ before inserting a new line. Second, we can freely move lines (e.g. using the shortcut SHIFT-ALT-[arrow up or down] in the IntelliJ-family IDEs) and also do not have to think about handling the last element in a different way. Finally, changes in the array result in a clear diff when using version control software like SVN and git.
…for Function Calls
While the above syntax was available for years, PHP 7.3 now allows the same syntax for function calls. Assume we want to merge arrays of color definitions:
<?php array_merge( $greenColors, $redColors, $yellowColors, );
You can already see why it would be inconsistent for a language to support this kind of syntax in the definition of arrays but not for function invocations. Finally with PHP 7.3, this syntax is also available.
…and for Function Declarations?
Now with those two examples in mind, wouldn’t it also make sense to support this syntax for function declarations? Consider this example:
<?php function someFunction( $firstArg, $secondArg, $thirdArg, );
There are hardly any compelling reasons why function declarations should not support trailing commas since this would be a backwards-compatible change and result in even more consistency. However, an RFC suggesting this exact idea was down-voted with 24 to 20 votes. Let’s hope for PHP 7.4.
- Original Request for Comments: https://wiki.php.net/rfc/trailing-comma-function-calls