Home PHP New features in PHP 8.1

New features in PHP 8.1

php8.1

PHP 8.1 is a major new version to PHP, which brings several new features, quality-of-life improvements, and attempts to prepare PHP to iron out some of its legacy features by deprecating and restricting certain undesired functionality.

PHP 8.1 is a continuation of PHP’s progress in providing a type system improvements. It also adds more features that encourages defensive programming.

Some of the highlights of PHP 8.1 include support for Enums, Fibers, never return type, Intersection Types, readonly properties, and first-class callable syntax. We will discuss about these in details below.

Enums

PHP 8.1 adds support for Enumerations. An Enumeration, or an Enum for short, is an enumerated type that has a fixed number of possible values.

A popular analogy for an Enum is suits in a deck of playing cards. A deck of playing cards has four suits, and they are fixed: ClubsDiamondsHearts, and Spades.

In PHP, these suits can be enumerated with an Enum:

enum Suit {
    case Clubs;
    case Diamonds;
    case Hearts;
    case Spades;
}

With Suit Enum, it is now possible to enforce types when accepting or returning a suit value:

function pick_card(Suit $suit) {}
pick_card(Suit::Clubs);
pick_card(Suit::Diamonds);
pick_card(Suit::Hearts);
pick_card(Suit::Spades);

In contrast to using special strings or numbers internally (i.e. magic numbers) to store and work with parameters, Enums make the application code more readability, and avoids unexpected application state.

Fibers

Fibers is a new feature in PHP 8.1 that brings lightweight and controlled concurrency to PHP.

In essence, a Fiber is a code block that maintains its own stack (variables and state), that can be started, suspended, or terminated cooperatively by the main code and the Fiber.

Fibers are similar to threads in a computer program. Threads are scheduled by the operating system, and does not guarantee when and at which point the threads are paused and resumed. Fibers are created, started, suspended, and terminated by the program itself, and allows fine control of the main program execution and the Fiber execution.

With Fibers, the code block within the Fiber can suspend the code block and return any data back to the main program. The main program can resume the Fiber from the point it was suspended.

It is important the concurrent execution does not mean simultaneous execution. Fiber by itself does not allow simultaneous execution of multiple Fibers or the main thread and a Fiber. However, it is a stepping stone for concurrent PHP frameworks to effectively manage their execution stack, and allow simultaneous execution.

Readonly Properties

PHP 8.1 brings support for read-only class properties. A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed.

Read-only class properties are declared with the readonly context-sensitive keyword in a typed property.

class User {
    public readonly int $uid;

    public function __construct(int $uid) {
        $this->uid = $uid;
    }
}

With a readonly property, overwriting the property, or writing to it from outside the class results in an Exception.

$user = new User(42);
$user->uid = 16; // Not allowed.

Intersection Types

PHP 8.1 supports Intersection Types, which allows declaring a type for a parameter, property, or return types and enforce that values belong to all of the declared class/interface types. This is the opposite of Union Types, which allows any of the declared types. PHP 8.1’s implementation of Intersection Types is called “pure” Intersection Types because combining Union Types and Intersection Types in the same declaration is not allowed.

Intersection Types are declared by combining the class/interface names with an & sign.

For a use-case example, consider PHP’s built-in Iterator and Countable interfaces. The Iterator interface makes it possible to iterate the class object using foreach. However, unless the same class implements Countable interface, it is not possible to call the count() function on such objects.

With an Intersection Type, it is now possible to type-check class objects to implement both Iterator and Countable interfaces.

function count_and_iterate(Iterator&\Countable $value) {
    foreach($value as $val) {}
    count($value);
}

In the snippet above, the $value parameter must be an object from class that implements both Iterator and Countable interfaces. Passing any other value causes a type error.

never return type

never is a new return type added in PHP 8.1.

A function/method that is declared with the never return type indicates that it will never return a value, and always throws an exception or terminates with a die/exit call.

never return type is similar to the existing void return type, but the never type guarantees that the program will terminate or throw. In other words, a function/method declared never must not call return at all, not even in the return; form.

function redirect(string $url): never {
    header('Location: ' . $url);
    exit();
}

New Hashing algorithms

PHP 8.1 adds support for xxHash and MurMurHash3 hashing algorithms. They are some of the fastest hashing algorithms, and can easily chew through data almost at the speed of a storage media. PHP is the first programming language to include these two hashing algorithms in its standard library.

These are few of the new features added in PHP 8.1. You can learn more about additional features in PHP 8.1 at php.net.

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Exit mobile version