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

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);
?>

Which output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Array spreading:

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

$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = array(...$arr1, ...$arr2, 111); //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

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

class CustomerData
{
    public function __construct(
        public string $name,
        public string $email,
        public int $age,
    ) {}
}

And use the array spreading to create the CustomerData object:

$input = [
    'age' => 25,
    'name' => 'Brent',
    'email' => 'brent@stitcher.io',
];

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

Which as the same behavior as:

$input = [
    'age' => 25,
    'name' => 'Brent',
    'email' => 'brent@stitcher.io',
];

$data = new CustomerData($input['age'], $input['name'], $input['email']);

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

class CustomerData
{
    public function __construct(
        public string $name,
        public string $email,
        public int $age,
    ) {}
}

$data = new CustomerData(
    name: $input['name'],
    email: $input['email'],
    age: $input['age'],
);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement