New in PHP 7.4
Although the new version of PHP is minor, it already brings many new, without exaggeration, cool features both for the syntax of the language and its performance. The list of innovations is not final, but the main changes have already been made and accepted. The release is scheduled for December 2019.
Key changes for the upcoming version:
Read more about these and other changes under the cat.
Disclaimer: Several times in my discussions with colleagues featured Brent's article “ New in PHP 7.4 ”. At first I wanted to make a translation, but in the process I realized that not all the latest updates are indicated in the text and there are some inaccuracies, so this article appeared instead of the translation.
Arrow functions allow you to make a shorter record of anonymous functions:
Some features of the adopted implementation of arrow functions:
You can read more about them in this article on Habr.
Hurrah! Class properties can now have type hint. This is a very long-awaited change since PHP 7 towards stronger typing of the language. Now we have all the basic features for strong typing. All types are available for typing, except
If you want me to consider in more detail the new possibilities of typing the properties of objects, note in the comments and I will write a separate article about them!
Instead of such a long entry:
Now it will be possible to write like this:
Now you can use the unpack operator in arrays:
Please note that this only works with non-associative arrays.
The external function interface (FFI) allows you to write C code directly in PHP code. This means that PHP extensions can be written in pure PHP.
It should be noted that this is a complex topic. You still need knowledge of C to use these features correctly.
Preloading is a terrific addition to the PHP core, which should lead to some significant performance improvements.
For example, if you use the framework, its files must be downloaded and recompiled for each request. When using opcache - the first time these files are involved in the processing of a request and then each time they are successfully checked for changes. Preloading allows the server to load the specified PHP files into memory at startup and to have them constantly available for all subsequent requests, without additional checks for file changes.
The performance improvement is “not free” - if the preloaded files are modified, the server must be restarted.
Currently, PHP has mostly invariant parameter types and invariant return types. This change allows you to change the type of the parameter to one of its supertypes. In turn, the returned type can be replaced by its subtype. Thus, this change will allow to more strictly follow the principle of substitution Barbara Liskov.
An example of using a covariant return type:
and contravariant argument:
Two new magic methods become available:
If you wrote something like this:
PHP would now interpret this as:
PHP 8 will interpret this differently:
PHP 7.4 adds an obsolescence warning when it detects an expression containing "." before the "+" or "-" and not surrounded by brackets.
Exception Support
Previously, exceptions could not be thrown out of the magic method
Libraries, such as those
Added Method
This function provides the same functionality as
Always Available Extension
This extension is now constantly available in all PHP installations.
PEAR is no longer actively supported, the core team decided to remove it from the default installation with PHP 7.4.
A new function has been added
Weak links allow you to save a link to an object that does not prevent the destruction of this object. For example, they are useful for implementing cache-like structures.
The absence of visual separators in groups of digits increased the time for reading and debugging the code, and could lead to unintentional errors. Now added support for the underscore character in numeric literals to visually separate groups of numbers.
Short opening tag
Key changes for the upcoming version:
- Typed Class Properties
- Preload for better performance
- Arrow functions for short writing anonymous functions
- Assigning union operator with null (?? =)
- Covariance / contravariance in legacy method signatures
- An external function interface that opens up new possibilities for developing extensions in PHP
- Unpacking operator in arrays
Read more about these and other changes under the cat.
Disclaimer: Several times in my discussions with colleagues featured Brent's article “ New in PHP 7.4 ”. At first I wanted to make a translation, but in the process I realized that not all the latest updates are indicated in the text and there are some inaccuracies, so this article appeared instead of the translation.
Arrow Functions ( RFC )
Arrow functions allow you to make a shorter record of anonymous functions:
array_map(function (User $user) {
return $user->id;
}, $users)
array_map(fn(User $user) => $user->id, $users)
Some features of the adopted implementation of arrow functions:
- They can access the
parent
area, so there is no need to use a keyworduse
. $this
also available, as in regular anonymous functions.- Arrow functions can contain only one line, which is also a return operator.
You can read more about them in this article on Habr.
Typed Properties ( RFC )
Hurrah! Class properties can now have type hint. This is a very long-awaited change since PHP 7 towards stronger typing of the language. Now we have all the basic features for strong typing. All types are available for typing, except
void
andcallable.
class Bar
{
public string $name;
public ?int $amount;
public Foo $foo;
}
If you want me to consider in more detail the new possibilities of typing the properties of objects, note in the comments and I will write a separate article about them!
Assign null join operator ( RFC )
Instead of such a long entry:
$data['date'] = $data['date'] ?? new DateTime();
Now it will be possible to write like this:
$data['date'] ??= new DateTime();
Array Unpacking Operator ( RFC )
Now you can use the unpack operator in arrays:
$arrayA = [1, 2, 3];
$arrayB = [4, 5];
$result = [0, ...$arrayA, ...$arrayB, 6 ,7];
// [0, 1, 2, 3, 4, 5, 6, 7]
Please note that this only works with non-associative arrays.
External Function Interface ( RFC )
The external function interface (FFI) allows you to write C code directly in PHP code. This means that PHP extensions can be written in pure PHP.
It should be noted that this is a complex topic. You still need knowledge of C to use these features correctly.
Preload ( RFC )
Preloading is a terrific addition to the PHP core, which should lead to some significant performance improvements.
For example, if you use the framework, its files must be downloaded and recompiled for each request. When using opcache - the first time these files are involved in the processing of a request and then each time they are successfully checked for changes. Preloading allows the server to load the specified PHP files into memory at startup and to have them constantly available for all subsequent requests, without additional checks for file changes.
The performance improvement is “not free” - if the preloaded files are modified, the server must be restarted.
Covariance / contravariance in legacy method signatures ( RFCs )
Currently, PHP has mostly invariant parameter types and invariant return types. This change allows you to change the type of the parameter to one of its supertypes. In turn, the returned type can be replaced by its subtype. Thus, this change will allow to more strictly follow the principle of substitution Barbara Liskov.
An example of using a covariant return type:
interface Factory {
function make(): object;
}
class UserFactory implements Factory {
function make(): User;
}
and contravariant argument:
interface Concatable {
function concat(Iterator $input);
}
class Collection implements Concatable {
function concat(iterable $input) {/* . . . */}
}
Custom Object Serialization ( RFC )
Two new magic methods become available:
__serialize
and __unserialize
. This serialization mechanism combines the versatility of an interface Serializable
with a __sleep/__wakeup
method implementation approach. More details on their differences can be found in the RFC.Concatenation Priority ( RFC )
If you wrote something like this:
echo "sum: " . $a + $b;
PHP would now interpret this as:
echo ("sum: " . $a) + $b;
PHP 8 will interpret this differently:
echo "sum :" . ($a + $b);
PHP 7.4 adds an obsolescence warning when it detects an expression containing "." before the "+" or "-" and not surrounded by brackets.
Exception Support __toString
( RFC )
Previously, exceptions could not be thrown out of the magic method
__toString
. The rationale for this behavior is that the conversion of objects to strings is performed in many functions of the standard library, and not all of them are ready to "process" exceptions correctly. As part of this RFC, a comprehensive audit of string conversions in the code base was performed, and this restriction can now be removed, which was done.Link Reflection ( RFC )
Libraries, such as those
symfony/var-dumper
, rely heavily on the exact derivation of variables ReflectionAPI
. Previously, there was no proper support for link reflection, which forced these libraries to rely on hacks to detect links. PHP 7.4 adds a class ReflectionReference
that solves this problem.Added Method mb_str_split
( RFC )
This function provides the same functionality as
str_split
, but for strings written in multibyte encodings.Always Available Extension ext-hash
( RFC )
This extension is now constantly available in all PHP installations.
PEAR is not enabled by default ( EXTERNALS )
PEAR is no longer actively supported, the core team decided to remove it from the default installation with PHP 7.4.
Password Hashing Algorithm Registry ( RFC )
A new function has been added
password_algos
that returns a list of all registered password hashing algorithms.Weak Links ( RFC )
Weak links allow you to save a link to an object that does not prevent the destruction of this object. For example, they are useful for implementing cache-like structures.
Number literal delimiter ( RFC )
The absence of visual separators in groups of digits increased the time for reading and debugging the code, and could lead to unintentional errors. Now added support for the underscore character in numeric literals to visually separate groups of numbers.
1_000_000_000 // int
6.674_083e-11; // float
299_792_458; // decimal
0xCAFE_F00D; // hexadecimal
0b0101_1111; // binary
0137_041; // octal
Short Open Tags Deprecated ( RFC )
Short opening tag
устарел и будет удалён в PHP 8. Короткий тег не пострадал.
Левоассоциативный тернарный оператор объявлен устаревшим (RFC)
Тернарный оператор имеет некоторые странные причуды в PHP. Этот RFC объявляет устаревшими вложенные тернарные операторы.
1 ? 2 : 3 ? 4 : 5; // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
В PHP 8 такая запись приведёт к ошибке уровня компиляции.
Обратно несовместимые изменения (UPGRADING)
Вот некоторые из самых важных на данный момент обратно несовместимых изменений:
- Вызов
parent::
в классе не имеющем родителя объявлен устаревшим. - Вызов
var_dump
на экземпляре DateTime
или DateTimeImmutable
больше не делает доступными свойства объекта. openssl_random_pseudo_bytes
выдаст исключение в ошибочных ситуациях, вызванных библиотекой OpenSSL. Раньше она возвращала false, что могло привести к генерации пустой строки.- Попытка сериализировать
PDO
или экземпляр PDOStatement
генерирует Exception
вместо PDOException
. - Вызов
get_object_vars()
на экземпляре ArrayObject
возвратит свойства самого ArrayObject
, а не значения обёрнутого массива. Чтобы как раньше получить значения обернутого массива — приведите ArrayObject
к типу array
.