12 December, 2019
The new stable version of PHP 7.4 is here. Released just a couple days ago on November 28th 2019, it introduced quite a few significant changes. They include new functions and syntax updates, which can go a long way to help you write more efficient code. In this article, we’re going to go over the most important new features of PHP 7.4.
PHP version 7.4 is not your everyday update. It includes a lot of new improvements, which may seem subtle at first, but go a long way to help you write better code. The overview includes but is not limited to the following features:
- Typed properties 2.0
- Improved type variance
- Null Coalescing Assignment Operator
- Array Spread Operator
- Arrow functions
- Numeric Literal Separator
Do you have experience with microservice architecture? 🤔 Take part in the State of Microservices 2020 survey!
Typed Properties 2.0
The latest version of PHP expands the concept of typed properties. Originally, it was only available for the arguments of a function. Now, the type can also be defined for the properties of each class.
It’s important to know that all PHP types with the exception of void and callable are available for the property of a class. When an illegal type is assigned, a Fatal Error exception will be returned.
If you want to know why void and callable were excluded, read up at PHP’s RFC.
Improved type variance (Covariant Returns and Contravariant Parameters)
Until now, all declarations in the parent class or interface had to be respected and taken into consideration when overwriting the methods of its child class. For example:
Now, PHP permits choosing less specific parameter types or more specific return types … :
… as well as and contravariant arguments:
The PHP 7.4 introduced preloading, which may be just what you need to improve the efficiency of your code. It’s built on top of OPCache. It compiles your files and then saves them in the memory. The OPCache itself has been present in PHP for quite some time, but it is only now when it can use preloading. How exactly does it work?
Long story short:
- You add paths to files to be loaded first.
- The scripts are run once when the server starts.
- All preloaded files are available in the memory for all requests.
- Any changes to the preloaded file will have no effect until the server is reloaded.
Null coalescing assignment operator
Starting with PHP 7.4, we can use a new assignment operator: ??=. Before, we used the ?? operator, which checked if a variable exists and then assigned a value to it.
With the ??=, the expression will now change to:
The ??= operator checks if the variable to the left exists. If it does, it leaves it as is. If the variable doesn’t exist, it assigns the value to the right to it. The operator shortens the usual expression, making it unnecessary to separately check and assign default values to variables. The code is much clearer to read as well (by the way – if you want more tips on this topic, read another of our articles and keep your PHP code clear).
Array spread operator
The spread operator (Spread Operator in Array Expression) is yet another new feature made available in PHP 7.4. It makes it possible to greatly limit the use of the array_merge function. The operator is built into the structure of the language, which makes it efficient and faster than array_merge,
Let’s see it in action:
We can also use the syntax of the generator:
The anonymous function has been a mainstay in PHP for a long time. But it took quite a lot of time to write it. Now, single line functions can be quickly converted into anonymous functions as “arrow functions”.
Numeric Literal Separator
PHP 7.4 makes it easy to add an underscore in order to visually separate numerical values.
The underscore is ignored by PHP. The change is purely cosmetic, making it easier to work with and operate on large numbers.
Foreign function interface
Among others, FFI allows us to easily write new PHP extensions in C and subsequently load it, e.g. through composer. You can read more about what FFI is at RFC.
To write an FFI extension, a good command of the C language is required. Accessing FFI data structure is twice slower than native PHP tables and objects. As a result, it makes no sense to use it to speed up your script, but it does when you want to reduce your memory usage.
The whole topic is quite complex. To get a deeper perspective, I highly recommend you read the RFC entry.
Custom object serialization
At present, we can take advantage of the _sleep and _wakeup methods as well as the Serializable interface. Unfortunately, both approaches have their limitations. A lot of them are amended by new methods introduced in PHP 7.4 – _serialize and _unserialize. Using them is a lot similar to the way we use the Serializable interface. Instead of calling the serialize() function, we directly return the data which would otherwise be serialized as tables. Let’s take a look:
This implementation solves the problem with Serializable, leaving the actual serialization and unserialization to the serializator’s implementation. There is no need to share the state of serialization, which makes it possible to avoid issues related to backreference ordering. We can also empty the calls to _unserialize() until the unserialization is over.
Again, more information and wider discussion on this topic is made available at RFC.
Reflection for references
Until now, libraries have been using all kinds of tricks in order to detect references. They are especially popular with libraries that take care of dumping, cloning or comparison over the value graph.
PHP ver. 7.4 is introducing the first-class API for reflection of references, which provides a solution for an old problem. The ReflectionReference class allows us to detect references. It also determines the reference equality. Since it’s a complex issue, the RFC is yet again a great go-to source to learn more about it.
Normally, as long as any object has a reference, it won’t be killed. The new WeakReference class allows us to add object references that do not prevent killing them This weak reference can be quite useful in cache-like structures. It makes it possible for the garbage collector to uncache objects for us.
A practical example:
The code above returns:
After the change:
This time, it returns:
The new PHP version introduces enough improvements so that anybody could find something for themselves. The new version is also supposed to be approx. 10% faster than the previous one. And that ‘s without preloading. Speed aside, the improved PHP will also be more object-oriented and orderly. But you also need to remember that PHP 7.4 contains some functions scheduled to be removed from the language. As it is usually the case, more about that at RFC.
Still need more practice with the new features? Try to experiment with what PHP 7.4 has to offer with docker. First, create a php file:
Now, run it in PHP 7.4:
Make sure to have a lot of fun with all that PHP has to offer!