PHP 7.4.0 is released
Yesterday (28 November, 2019), the PHP development team has announced the immediate availability of PHP 7.4.0 and it has given us numerous features such as:
Highlights
- Typed Properties
- Numeric Literal Separator
- Spread Operator for Arrays / Unpacking Inside Arrays
- Short Arrow Functions
Other Features
- Weak References
- Allow Exceptions from __toString()
- Opcache Preloading
- Several Deprecations
- Extensions Removed from the Core
Typed properties
Class properties now support type declarations. The below example will enforce that $user->id
can only be assigned integer values and $user->name
can only be assigned string values.
<?php
class User {
public int $id;
public string $name;
}
?>
Numeric Literal Separator
Numeric literals is now able to contain underscores between digits.
<?php
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
?>
Spread Operator for Arrays / Unpacking Inside Arrays
As community voted in support of Spread Operator for array in favor to add it in PHP 7.4.0 release. See this: https://wiki.php.net/rfc/spread_operator_for_array#vote
The spread operator support for argument unpacking first existed in PHP 5.6 release. Now the community expanded on the usage to arrays; both arrays and objects that support traversable can be expanded.
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];$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]function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c']; // ['a', 'b', 'c']$arr7 = [...new ArrayIterator(['a', 'b', 'c'])]; // ['a', 'b', 'c']function arrGen() {
for($i = 11; $i < 15; $i++) {
yield $i;
}
}
$arr8 = [...arrGen()]; // [11, 12, 13, 14]
Short Arrow Functions
The PHP team recently approved the Short Arrow Functions proposed by the community members Nikita Popov, Levi Morrison, and Bob Weinand.
$extended = function ($c) use ($callable, $factory) {
return $callable($factory($c), $c);
};
// with arrow function:
$extended = fn($c) => $callable($factory($c), $c);
Reference