What’s New in PHP 7.4: Salient Features of the Beta Release
We have a new PHP version release with us, that is PHP 7.4. Continuing with the tradition, I will highlight some salient PHP 7.4 features in this article. So, that our wide community and customers always stay aware of the changes, deprecation and new features added in the latest version.
The new PHP 7.4 released on November 28th, 2019. I recommend you not to upgrade your production servers with PHP 7.4, as you can break things up very quickly while hosting PHP website. PHP 7.4 comes with so many popular features that community members had already started mentioning before. I will discuss all of them later in detail.
You should also know that PHP 7.4 is now in feature freeze state and the contributors have already started working on PHP 8. So, the next PHP release could really come as a landmark in the evolution of the language. Fingers crossed for that!
PHP 7.4 Features, Deprecation and Updates
There are many significant changes in PHP 7.4. Having some deprecation also in bucket, some of the listed items are:
- Support for Typed Properties
- Support for Arrow Functions
- Covariant Returns and Contravariant Parameters
- Support for coalesce assign (??=) operator
- Support for WeakReferences
- Preloading
- Spread Operator in Array Expression
- Deprecations
I will discuss each of the features and changes in PHP 7.4 in detail. Afterwards, I will also explain what deprecations are made in the new PHP 7.4.
Support for Typed Properties
Typed properties have been missing in PHP since long. They are now available in PHP 7.4. By using them, you can easily declare type hints to the class variables and properties. Before, it was not possible and you had to create getter and setter methods to enforce type contracts.
Also, you can declare types on static properties which was not allowed earlier, following the same declaration methods for class variables and properties.
Let’s see the example Class provided by RFC:
- Class User {
- /** @var int $id */
- private $id;
- /** @var string $name */
- private $name;
- public function __construct(int $id, string $name) {
- $this->id = $id;
- $this->name = $name;
- }
- public function getId(): int {
- return $this->id;
- }
- public function setId(int $id): void {
- $this->id = $id;
- }
- public function getName(): string {
- return $this->name;
- }
- public function setName(string $name): void {
- $this->name = $name;
- }
- }
Using the new method, you can write the above example as:
- class User {
- public int $id;
- public string $name;
- public function __construct(int $id, string $name) {
- $this->id = $id;
- $this->name = $name;
- }
- }
You can define static types as follows:
public static iterable $staticProp;
These types are allowed to use except callable and void.
- Int
- Float
- String
- Iterable
- Array
- Object
- Self
- Parent
- Bool
If you try to assign a different value from the type, PHP will throw a comprehensive message. Let’s see the example in which $name is declared as string, and array assigned to the value. Check out the error below.
- Class User {
- public int $id;
- public string $name;
- }
- $user = new User;
- $user->id = 42;
- $user->name = [];
- // Uncaught TypeError: Typed property User::$name // must be string, array used
Support for Arrow Functions
Anonymous functions are mostly used in Javascript & it’s frameworks and looks quite verbose in PHP. As arrow function allows the usage of short closures for creating one line functions. This helps in writing simple and neat code. Let’s see the example of arrow function in PHP 7.4
- $factor = 10;
- $nums = array_map(fn($num) => $num * $factor, $nums);
There is no need to declare use() in arrow function as it has access to the parent scope already. Also, you can declare the type hinted statements in functions which always start with fn.
Covariant Returns and Contravariant Parameters
PHP has the most invariant parameter and return types and the supertype and subtype must have the same constraint for return type and parameter type. When determining the compatibility of a method with its parent, the engine should permit less specific parameter types, and more specific return types as long as the new types still accept the types specified by the parents.
In other words, a parameter type can be substituted for one of its supertypes and a return type can substitute a subtype, and you can use covariant types in latest PHP version. The following code will now work:
- class A {}
- class B extends A {}
- class Producer {
- public function method(): A {}
- }
- class ChildProducer extends Producer {
- public function method(): B {}
- }
Support for Coalesce Assign (??=) Operator
PHP 7.4 has also introduced shorthand method for coalesce assign operator. This RFC proposes that despite ?? coalescing operator being a comparison operator, coalesce equal or ??= operator is an assignment operator. If the left parameter is null, assign the value of the right parameter to it. If the value is not null, nothing is made.
Let’s see an example on how you can use the coalesce operator in PHP 7.4:
- $someArray['key'] ??= 'someValue';
instead of
- $someArray['key'] = $someArray['key'] ?? 'someValue';
Therefore, If the value of left hand parameter is null, the method will automatically copy the value of right hand parameter.
Support for WeakReferences
PHP 7.4 now supports Weak References. Weak References allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. In simple terms, weakrefs can work like a cache structure.
Currently, you can use weak reference by installing the PECL extension pecl-weakref. Note that you cannot serialize them in a simple manner. Here’s an example how you can write a weak reference.
- <?php
- $obj = new stdClass;
- $weakref = WeakReference::create($obj);
- var_dump($weakref->get()); // object(stdClass)#1 (0) {}
- unset($obj);
- var_dump($weakref->get()); // NULL
- ?>
At first, you will get the object, and after unsetting it, you will get null.
Preloading
While working with PHP, you can always configure opcache for faster PHP 7.4 performance. Basically opcache compiles the code files first, and then saves them in shared memory to avoid the repetition of compilation in later stages. This concept of loading files in opcache is called Preloading.
Earlier in PHP 7.4, the official RFC proposed new changes with the renewed concept. Let’s see what official proposal highlighted:
“On server startup – before any application code is run – we may load a certain set of PHP files into memory – and make their contents “permanently available” to all subsequent requests that will be served by that server. All the functions and classes defined in these files will be available to requests out of the box, exactly like internal entities (e.g. strlen() or Exception). In this way, we may preload entire or partial frameworks, and even the entire application class library”
To carry out preloading, you can now specify a single directive opcache.preload in PHP.ini file and give the path or name of any single PHP file. Once the file is preloaded, you can use it anytime during your project. In this way you can upload your files at the startup and they will be permanently available for all the requests, at anytime. Hence practicing this, you can achieve significant performance boost for overall application. You can read its detailed implementation here.
Spread Operator in Array Expression
In PHP 7.4, you can now use spread operators in arrays. They are faster then array_merge and increases PHP 7.4 performance by a fair margin. Although, PHP has supported spread operators since PHP 5.6, but now they are also available for array expressions.
For example,
- $parts = ['apple', 'pear'];
- $fruits = ['banana', 'orange', ...$parts, 'watermelon'];
- // ['banana', 'orange', 'apple', 'pear', 'watermelon'];
- Spread operator works for both array syntax(array()) and short syntax([]).
- $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]
For detailed explanation you can see the official RFC.
Deprecations in PHP 7.4
New features always come with the depreciation of old features or components. PHP 7.4 has come up with some known deprecations as well. Lets see what they are:
Short Open Tags
Short open tags ?> are now deprecated and will be completely removed in PHP 8.0.
Left-Associative Ternary Operator
Ternary operator in PHP is left-associative rather then right-associative like other languages. This behavior is not so useful in PHP. This latest version proposes to deprecate and remove left-associativity for the ternary operator and requires explicit use of parentheses instead.
For example:
- 1 ? 2 : 3 ? 4 : 5; // deprecated
- (1 ? 2 : 3) ? 4 : 5; // ok
- 1 ? 2 : (3 ? 4 : 5); // ok
Deprecate Curly Brace Syntax
In PHP, you can use curly braces and square brackets to access array elements. But in PHP 7.4, you can not use curly braces as it will throw parse error.
- $array[] = 3;
- echo $array[2]; // prints 3
- $array{} = 3; // Parse error: syntax error, unexpected '}'
Road to PHP 8.0
You can now download the latest version of PHP and can test it on dev servers. It is not recommended to use PHP 7.4 version on production servers and live applications, as it can break up some things that are still not compatible with it.
After PHP 7.4 I’m excited about PHP 8.0 which is a major version update and introduces significant new features to increase performance and security. The most awaited feature is JIT that will be included and fully functional in PHP 8. Contributors are working hard to make this major version available with dev related feature so that it eases various developmental tasks.
Final words
So, this brings to the end of this article which thoroughly demonstrated all the latest PHP 7.4 features. As the situation stands, this new PHP version looks to be more powerful as compared to its predecessors. Moreover, it will ease various development tasks of the developers, as its new updated functions are precisely built for the modern web applications.
If you still want to know more about PHP 7.4 or have some questions regarding this article, please feel free to ask them below in the comments section.
Comments
Post a Comment