Skip to content
Advertisement

What’s the difference between upcoming PHP8’s spread operator and it’s pre-existing compact function? [closed]

What’s the difference between upcoming PHP8’s spread operator and it’s pre-existing compact() function ?

$data = new CustomerData(...$input);

Advertisement

Answer

Differences between Compact and Spread Operator

Compact PHP function:

compact — Create array containing variables and their values

JavaScript

Which output:

JavaScript

Array spreading:

while array spreading merge two or more array without adding a key to his value (associative array):

JavaScript

Also array spreading can be used to fill arguments of a method call, assume that you have this constructor to your class:

JavaScript

And use the array spreading to create the CustomerData object:

JavaScript

Which as the same behavior as:

JavaScript

PHP has already supported argument unpacking (AKA spread operator) since 5.6. This RFC proposes to bring this feature to array expression.

Also spread operator in array expression is implemented since PHP 7.4.

Sources:

PHP: compact – Manual

PHP: Spread Operator in Array Expression

Upcomming PHP 8: named arguments

From: PHP 8: named arguments

Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent, and allows skipping default values arbitrarily

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement