Updates in PHP 8.1


These changes include:

enum support. Instead of a class with constants, you can now use the following construction:

 enum Status {

     case pending;

     case Active;

     case Archived;

   }

   class Post

   {

       public function __construct(

           private Status $status = Status::Pending;

       ) {}

       public function setStatus(Status $status): void

       {

        // …

       }

   }

   $post->setStatus(Status::Active);

support for lightweight streams or fibers (Fiber) with the ability to manage these streams at a low level. Fibers, on the other hand, allow you to define blocks of code, the execution of which can be suspended and resumed, similar to generators, but from any position on the stack. They make it possible to use the same API in blocking and non-blocking code. Fiber support will be added to the Amphp and ReactPHP frameworks:

 $fiber = new Fiber(function (): void {

       $valueAfterResuming = Fiber::suspend(‘after suspending’);

       // …

   });

   $valueAfterSuspending = $fiber->start();

   $fiber->resume(‘after resuming’);

improved implementation of the object code cache (opcache) with the ability to cache information about class inheritance. This will improve the performance of some applications by 5-8%;

optimization of JIT operation, implementation of JIT support for ARM64 architecture (AArch64), acceleration of class name resolution, optimization of timelib and ext/date libraries, performance improvement of serialization and deserialization, optimization of get_declared_classes(), explode(), strtr(), strnatcmp() functions and dexx(). Symfony Demo performance increased by 23% and WordPress by 3.5%;

inclusion of an unpacking operator inside “…$var” arrays, which will allow substituting existing arrays when defining a new one, expanding support for string keys. Now you can use it in code:

 $array1 = [“a” => 1];

   $array2 = [“b” => 2];

   $array = [“a” => 0, …$array1, …$array2];

   var_dump($array); // [“a” => 1, “b” => 2]

using the “new” keyword in initializers to use objects as default parameter values, static variables, global constants, and attribute arguments, and when creating nested attributes:

class MyController {

       public function __construct(

           private Logger $logger = new NullLogger(),

       ) {}

   }

the ability to mark class properties for read-only access (information in such properties can be written only once):

 class PostData {

       public function __construct(

           public readonly string $title,

           public readonly DateTimeImmutable $date,

       ) {}

   }

   $post = new Post(‘Title’, /* … */);

   $post->title = ‘Other’;

   > Error: Cannot modify readonly property Post::$title

new syntax for callable objects – a closure can now be formed by calling a function and passing it the value “…” as an argument (i.e., to get a function reference, you can use myFunc(…) instead of Closure:: fromCallable(‘myFunc’)):

 function foo(int $a, int $b) { /* … */ }

   $foo = foo(…);

   $foo(a: 1, b: 2);

full support for type intersections (intersection types) to create new types whose values ​​must fall under several types at the same time. Intersections require the presence in the set to be filled not of any of the listed types, but of all of the specified types:

  function count_and_iterate(Iterator&Countable $value) {

      foreach ($value as $val) {

          echo $val;

      }

      count($value);

   }

a new “never” type that can be used to inform static analyzers that a function is terminating program execution, for example by throwing an exception or executing the exit function:

   function dd(mixed $input): never

   {

      exit;

   }

new function array_is_list, which allows you to determine that the keys in the array are in ascending order of numerical values, starting from 0:

   $list = [“a”, “b”, “c”];

   array_is_list($list); // true

   $notAList = [1 => “a”, 2 => “b”, 3 => “c”];

   array_is_list($notAList); // false

   $alsoNotAList = [“a” => “a”, “b” => “b”, “c” => “c”];

   array_is_list($alsoNotAList); // false

you can now use the “final” keyword to prevent redefining parent class constants:

class Foo

   {

       final public const X = “foo”;

   }

   class Bar extends Foo

   {

      public const X = “bar”;

> Fatal error: Bar::X cannot override final constant Foo::X

   }

functions fsync and fdatasync to force saving changes from the disk cache:

  $file = fopen(“sample.txt”, “w”);

   fwrite($file, “Some content”);

   if (fsync($file)) {

       echo “File has been successfully persisted to disk.”;

   }

   fclose($file);

the ability to use prefixes “0o” and “0O” for octal numbers, in addition to the previously used prefix “0”:

 016 === 0o16; // true

   016 === 0O16; // true

selectively limiting the use of $GLOBALS, which will lead to a violation of backward compatibility, but will make it possible to significantly speed up operations with arrays. It is forbidden to write to $GLOBALS and pass $GLOBALS by pointer. An analysis of 2000 packages showed that only 23 of them would be affected by this change. For example, support for expressions such as:

   $GLOBALS = [];

   $GLOBALS += [];

   $GLOBALS =& $x;

   $x =& $GLOBALS;

   unset($GLOBALS);

   by_ref($GLOBALS);

rejection of implicit incompatible conversion of floating point numbers (float) to integer representation (int), leading to loss of precision. The change applies to array key value conversions, integer type enforcement, and integer-only operators:

   $a = [];

   $a[15.5]; // deprecated, as key value loses the 0.5 component

   $a[15.0]; // ok, as 15.0 == 15

internal methods should now return the correct type. Otherwise, warnings will be displayed, and in PHP 9.0 they will be replaced with an error;

work on transferring functions from using resources to manipulating objects. Functions finfo_* and imap_* have been transferred to objects;

not passing null values ​​as arguments to internal functions marked as non-nullable. In PHP 8.1, using str_contains(“string”, null) constructs will result in a warning, but in PHP 9, an error;

rejection of the Serializable programming interface;

many modules convert resources to objects (file_info -> finfo to FileInfo, FTP\Connection, IMAP\Connection, LDAP\Connection|Result, PgSql\Connection|Result, PSpell\Dictionary, GdFont to GD, etc.);

support for MurmurHash3 and xxHash hashing algorithms.

On November 22, 2021, the PHP language community established the PHP Foundation, a non-profit organization. Its goal is to create a structure responsible for organizing the financing and promotion of the PHP project, including supporting the developer community, hiring them and providing them with the necessary conditions for the development of the project. On the basis of the PHP Foundation, a system of joint financing of project contributors is already operating. As investors, both companies and individuals can take part in it. In 2022, the PHP Foundation plans to start issuing developer grants as the organization’s budget expands.

Leave a Reply

Your email address will not be published. Required fields are marked *