
PHP 7.4.0 is coming shortly, this is what the development has announced and in this article we will list some of the new features in this release.
Some of new features added in this release:
- Typed Properties
- Arrow Functions
- Limited Return Type covariance and argument type contravariance
- Null coalescing assignment operator
- Unpacking inside arrays
- Numeric literal operator
- Allow exceptions from __toString()
Typed Properties
Class properties now support type declarations.
<?php class Product { public int $id; public string $title; public float $price; public boolean $is_new; } ?>
In this example the user is enforced to supply integer $product->id and string $product->title and float $product->price and boolean $product->is_new.
Arrow functions
PHP 7.4.0 support short syntax arrow functions just like Javascript ES6, consider this example:
<?php $factor = 10; $nums = array_map(function($value) use ($factor) { return $value * $factor; }, [1, 2, 3, 4]); ?>
With arrow functions:
<?php $factor = 10; $nums = array_map(fn($value) => $value * $factor, [1, 2, 3, 4]); ?>
Limited Return Type covariance and argument type contravariance
<?php class A {} class B extends A {} class Producer { public function method(): A {} } class ChildProducer extends Producer { public function method(): B {} } ?>
In this code the ChildProducer class extends from Producer class but ChilderProducer::method() return B type, although Producer::method() return A type.
Null coalescing assignment operator
Now checks like this:
<?php if (!isset($array['index'])) { $array['index'] = 1; }
Can be rewritten with:
<?php $array['index'] ??= 1;
Unpacking inside arrays
Now you can extract arrays inside other arrays to produce a new array like this:
<?php $parts = ['apple', 'pear']; $fruits = ['banana', 'orange', ...$parts, 'watermelon']; // ['banana', 'orange', 'apple', 'pear', 'watermelon']; ?>
Numeric literal operator
Numeric literals allow values to contain underscores between digits.
<?php 6.674_083e-11; // float 299_792_458; // decimal 0xCAFE_F00D; // hexadecimal 0b0101_1111; // binary ?>
Allow exceptions from __toString()
You can now throw exceptions in __toString() in php 7.4.0. In the previous versions this can lead to fatal errors.
class MyClass { public function __toString() { if($error) { throw new \Exception("can't represent class to string representation"); } } }
For a full list of features refer to php.net