View code


What's New in PHP 8.2?

PHP is evolving at a fast pace, and with each new version, we get new features and improvements. In this article, we will explore the new features and changes that are coming in PHP 8.2.

Allow null, true, and false as standalone types

With the introduction of Union Types in PHP 8.0, we could use null and false as part of a union type.

public function name(): string|null
{}
public function isVerified(): int|false
{}

However, we couldn't use null or false as standalone types, in PHP 8.2, we can.

public function isNotVerified(): false
{}

PHP 8.2 also adds support for true as a standalone type. As a result, we have the following:

public function isVerified(): true
{}
public function isNotVerified(): false
{}
public function alwaysNull(): null
{}

Readonly classes

PHP 8.1 added support for readonly properties, but can't lie it drives me crazy that they added support for readonly properties without readonly classes. In PHP 8.2, we can finally have readonly classes. PHP 8.1

class User
{
public readonly string $name;
public readonly string $email;
}

PHP 8.2

readonly class User
{
public string $name;
public string $email;
}

It is important to understand that readonly classes are not the same as non-readonly classes, so let's explore the differences.

  • Declaring a class as readonly means that all properties of that class are readonly. We can't have a mix of readonly and non-readonly properties in a readonly class.
  • We can't have dynamic properties in a readonly class. This is a good thing for the future of PHP, as it wil help PHP to become more strict.
  • If you extend a readonly class, the child class must also be readonly.
  • Keep in mind that while readonly classes ensure partial immutability, they do not guarantee it entirely. Despite being the perfect fit for value-objects, promising the invariability of their data, the objects contained in a readonly property are susceptible to changes. This is identical to the functionality of readonly properties.

Random - For real this time