Blog Detail

26

Nov
 Latest features and Updates of PHP 8.1 - PHP 8.1 Released cover image

arrow_back Latest features and Updates of PHP 8.1 - PHP 8.1 Released

Finally, PHP 8.1 is released on 25 November 2021 with a lot of new and exciting peculiarities. PHP 8.1 is a major update of the PHP language.
It includes many new features, including enums, read-only properties, first-class callable syntax, intersection types, fibers, performance improvements, and more. So in this post, I want to share the new updates and features and their actual impact of PHP 8.1 on our code that I’ve witnessed.

Added Enumerations

Finally, The most awaited feature of Php 8.1 is here. Now we can use an enum instead of a set of constants and get validation out of the box.

Before Php 8.1



class Status
{
  const DRAFT = 'draft';
  const PUBLISHED = 'published';
  const ARCHIVED = 'archived';
}
function acceptStatus(string $status) {...}

After Php 8.1

enum Status
{
  case Draft;
  case Published;
  case Archived;
}
function acceptStatus(Status $status) {...}

Readonly Properties

PHP 8.1 brings support for read-only class properties. Once again, this feature is such a quality-of-life improvement. A class property declared read-only is only allowed to be initialized once, and further changes to the property are not allowed.
Read-only class properties are declared with the readonly keyword in a typed property. Read-only property values can only be set from within the class itself, either from the constructor or another method. Once set, no further modifications are allowed to that property, even from within the class.

Before Php 8.1

class BlogData
{
  private Status $status;
  
  public function __construct(Status $status)
  {
     $this->status = $status;
  }
  
  public function getStatus(): Status
   {
    return $this->status;  
  }
}

After Php 8.1

class BlogData
{
  public readonly Status $status;
  
  public function __construct(Status $status)
  {
     $this->status = $status;
  }
}

New in initializers

PHP 8.1 adds a feature that might seem like a small detail, but it will have a significant day-by-day impact on many people. After the release of Php 8.1, Now you can use objects as default parameter values, static variables, and global constants, as well as in attribute arguments. So this effectively makes it possible to use nested attributes.

Before Php 8.1

class User
{
   /**
   * @Assert\All({
   *   @Assert\NotNull,
   *   @Assert\Length(min=5)
   * })
   */
   public string $name = '';
}

After Php 8.1

class User
{
   #[\Assert\All(
     new \Assert\NotNull,
    new \Assert\Length(min: 6))
  ]
  public string $name = '';
}

First-class Callable Syntax

PHP 8.1 also supports a new syntax in creating a callable from within the current scope. With this new syntax, it is simpler to create a callable using the same syntax a function/method is called, instead of utilizing Closure::fromCallable.
Closure::fromCallable returns a callable (Closure object) from a PHP callable (function name, method, or anonymous function). The first-class callable syntax aims to overcome the boilerplate code of Closure::fromCallable.

Before Php 8.1

$foo = [$this, 'foo'];
$fn = Closure::fromCallable('strlen');

After Php 8.1

$foo = $this->foo(...);
$fn = strlen(...);

Fibers

Fiber is a unique feature in PHP 8.1 that offers lightweight and controlled concurrency to PHP. They are a means of creating code blocks that can be paused and resumed like Generators, but from anywhere in the stack. Fibers themselves don’t magically render concurrency, There still needs to be an event loop. However, they provide blocking and non-blocking implementations to share the same API.

Fibers allow getting rid of the boilerplate code previously seen with Promise::then() or Generator-based coroutines. Libraries will generally build further abstractions around Fibers, so there’s no inadequacy to interact with them directly.

Before Php 8.1

$httpClient->request('https://example.com/')
    ->then(function (Response $response) {
      return $response->getBody()->buffer();
    })
    ->then(function (string $responseBody) {
      print json_decode($responseBody)['code'];
    });

After Php 8.1

$response = $httpClient->request('https://example.com/');
print json_decode($response->getBody()->buffer())['code'];

There are still more features in PHP 8.1, but these are the ones I’m most passionate about. So if you want to explore all features of Php 8.1 you can visit here.

Published at : 26-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project