AMZ DIGICOM

Digital Communication

AMZ DIGICOM

Digital Communication

PHP 8: all the new features of the latest version of PHP

PARTAGEZ

PHP is one of the easiest programming languages ​​to learn. With a good PHP tutorial and the right motivation, you can write your first scripts in a few hours and run commands. PHP 7 has already made it possible to optimize its speed, which led to a better ranking. The open source language has been the subject of a new major update with version 8.0. Followed a year later by a minor update with version 8.1.

What are the features of PHP 8.1?

PHP 8.1 was released on November 25, 2021. Here are the new features he brought:

  • Enum : Enums (enumerations with a certain number of values) are now available as a variable type.
  • Fibers : The new Fibers code block type gives you the ability to interrupt functions and resume them later, so that multiple threads can run concurrently (not in parallel).
  • Arrays : Since PHP 7.4, you can unwrap arrays with numeric keys. This is also possible for keyed arrays containing character strings.
  • Readonly : from now on, class properties can be marked as ‘readonly’ and are therefore no longer modifiable.
  • Intersection : Intersection types (similar to union types) are now available.
  • Never : the new return type ‘never’ indicates that a function never returns, but for example throws an exception or terminates the script.
  • Final : You can now mark class constants with ‘final’ so that they cannot be modified by subclasses.
  • Fsync : PHP 8.1 introduces the two functions ‘fsync’ and ‘fdatasync’ to synchronize data from buffer to storage media.
  • Octal : in order to display the octal number system, it will be possible in the future to use the prefix ‘0o’ (zero and small O) in addition to ‘0’ (zero).
  • Globals : The use of ‘$GLOBALS’ has been slightly restricted and now leads to an error message in some cases.
  • Null : Passing null values ​​to non-nullable arguments of internal functions is now deprecated and triggers a deprecation warning.

PHP 8: released in November 2020

On November 26, 2020, a new major version of the popular scripting language, PHP 8.0.0, was released. Its predecessor PHP 7.4 had been released a year earlier, just after support for PHP 7.1 was discontinued. Support for PHP 7.2 also ended at the end of 2020.

Try PHP 8 now!

Try PHP 8 now! You are not yet an IONOS customer? Opt for one of our economical web hosting offers. In your IONOS customer area, you can change the current version of PHP to PHP 8.

Are there any complications with the old code?

As PHP 8 is a new major version, it is to be expected that old code will no longer be compatible. However, most of the changes that could cause complications were already deprecated in the versions 7.2, 7.3 And 7.4.

Some of the latest changes include:

  • Tea real kind
  • Magic quotes legacy
  • array_key_exists() with objects
  • FILTER_SANITIZE_MAGIC_QUOTES filter
  • Reflection export() methods
  • mb_strrpos() with encoding as 3rd argument
  • implode() parameter order mix
  • Unbinding $this from non-static closures
  • hebrevc() function
  • convert_cyr_string() function
  • money_format() function
  • ezmlm_hash() function
  • restore_include_path() function
  • allow_url_include ini directive

If you have always kept your code up to date, you will have virtually no problems, even if this major release brings non-backwards compatible changes. A complete list of changes for this Major Release is available in the PHP project page.

Note

Microsoft has announced that it will no longer offer Windows support for PHP 8 and later versions. However, PHP developers have already announced their intention to fill this gap themselves.

The new features of PHP 8

The new version of PHP comes with new features that will provide web developers with many additional possibilities. Here is a summary of the main improvements made compared to previous versions.

Note

THE November 30, 2020PHP version 7.2 has reached its official end of life date (EOL for End-Of-Life) and has since been unsupported. To learn more about this, see our article on this topic.

JIT compiler

The biggest innovation is the JIT compiler, which significantly improves performance. PHP first translates the source code into intermediate code (opcodes), which the Zend Engine then executes. The JIT compiler (JIT = Just in Time) translates parts of the code directly into machine code during execution and therefore acts as a cached version of the code.

This new feature of PHP 8 has already been tested quite impressively by Pedro Escudero. The latter used a simple script to compare versions 5.3, 7.4 and 8 (with and without JIT). So, he ran the script 100 times in each version and then calculated the average time needed for execution.

The following average values ​​were therefore obtained:

Version Time in seconds
5.3 0.64574003219604
7.4 0.10253500938416
8 (without JIT) 0.098223924636841
8 (with JIT) 0.053637981414795

If the transition from version 7.4 to version 8 without JIT does not make much difference, the difference compared to version 8 with JIT is significant. The JIT compiler allows a performance improvement of more than 45%.

Union type

Union types have already appeared in other languages ​​such as C/C++, TypeScript or Haskell. Here two or more types can form a union and any mentioned type can be used. In the code itself, we could for example have:

public function foo(Foo|Bar $input): int|float;

php

However, there is a restriction, because void cannot be part of a union type, because it does not produce a return value. In addition, null unions can be declared with the mentions |null Or ? , as in this example:

public function foo(Foo|null $foo): void;
public function bar(?Bar $bar): void;

php

Static return type

Static is a special class name; in the new version it becomes a valid Return type in addition to self & parent.

WeakMap

WeakRefs has already been added to PHP 7.4. PHP 8 now provides the extension of this function with WeakMaps. WeakMaps and WeakRefs can be used to remove objects when only the cache references the feature classes of the objects. This allows save resources when handling objects. An example from the documentation:

class FooBar {
    private WeakMap $cache;
    public function getSomethingWithCaching(object $obj) {
        return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);
    }
    // ...
}

php

::class applied to objects

In previous versions, you had to use get_class() to get the class name of an object. Now you can apply ::class to objects, which reduces the size of the source code.

Stringable interface

The Stringable interface is automatically added to classes that implement the __ methodtoString(). Previously, this step had to be done manually. In the code itself, this is what it looks like:

class Foo
{
    public function __toString(): string
    {
        return 'foo';
    }
}
function bar(string|Stringable $stringable) { /* … */ }
bar(new Foo());
bar('abc');

php

fdiv() function

With the new fdiv() function, division by 0 is allowed. You then get INF, -INF Or NAN as the return value.

Type errors

Previously, only user-defined functions triggered the TypeErrorsthe internal functions issued a warning and null. With PHP 8, the majority of internal functions also return TypeErrors.

New classification of engine warnings

Until now, we noted many errors which only appeared in the form of a warning or a note. An update has now been made. A complete list of new PHP error messages is available in the documentation.

Correct signatures of magical methods

In previous versions of PHP it was possible to write magic methods with signatures that did not match the expected signature, e.g. __clone(): float Or __isset(): Closure. Since the introduction of PHP 7.0, the correct use of magic methods has only been checked randomly. Various parameter and return value checks have been added to the new version to ensure the correctness of signatures.

Reflection

Reflection signatures have been changed. Originally, Reflection was specified as follows:

ReflectionClass::newInstance($args);
ReflectionFunction::invoke($args);
ReflectionMethod::invoke($object, $args);

php

With PHP 8, this will be written as follows:

ReflectionClass::newInstance(...$args);
ReflectionFunction::invoke(...$args);
ReflectionMethod::invoke($object, ...$args);

php

To support PHP 7 and PHP 8 at the same time, you can write the code like this:

ReflectionClass::newInstance($arg = null, ...$args);
ReflectionFunction::invoke($arg = null, ...$args);
ReflectionMethod::invoke($object, $arg = null, ...$args);

php

Advice

Don’t have your own website yet? Web hosting from IONOS is powerful and also suitable for beginners. With virtual servers from IONOS, you can also count on a particularly high level of flexibility and the best performance. Choose the offer that best suits your project.

Télécharger notre livre blanc

Comment construire une stratégie de marketing digital ?

Le guide indispensable pour promouvoir votre marque en ligne

En savoir plus

Souhaitez vous Booster votre Business?

écrivez-nous et restez en contact