What are the New Changes in PHP 8.2?

PHP 8.2 is releasing on 24th November 2022. PHP is in the stages of stabilization; therefore, you should not expect any changes. In this blog, I will discuss all the new features and performance improvements one by one.

Readonly Classes

Readonly properties were first introduced in PHP 8.1. In PHP 8.2, there have been some syntax changes to apply Readonly to each class property. Earlier it was written as:

class Post
{
    public function __construct(
    public read-only string $title,
    public readonly Author $author,
    public readonly string $body,
    public readonlyDateTime $publishedAt,
    ) {}
}

Now, you can write as follows:

readonly class Post
{
    public function __construct(
    public string $title, 
    public Author $author,
    public string $body,
    public DateTime $publishedAt,
    ) {}
}

Allow Constant in Traits

In PHP, we can reuse codes known as traits. Currently, we can only define methods and properties in traits, not constants. But, PHP 8.2 will allow defining constants in traits, similar to how we define class constants.

Example:

trait Foo {
    public const FLAG_1 = 1;
    protected const FLAG_2 = 2;
    private const FLAG_3 = 2;
    
    public function doFoo(int $flags): void {
    	if ($flags & self::FLAG_1) {
    		echo 'Got flag 1';
    	}
   		if ($flags & self::FLAG_2) {
    		echo 'Got flag 2';
    	}
    	if ($flags & self::FLAG_3) {
    		echo 'Got flag 3';
    	}
    }
}

Random Extension Improvement

Presently, the random functionality of PHP relies on the Mersenne Twister state. It is stored in the global area of PHP, and a user can not access it. The addition of randomization functions in between the codes breaks them. The complexity is even higher when the code uses external packages. Thus, the current random functionality of PHP fails to produce random values consistently. The PHP team has noted all these issues and will lead to improvements after a valid consensus.

Null, true and false as standalone types

In PHP 8.2, null, true and false are valid types, and you can use them by yourselves. A common example is the built-in function of PHP, where false is used as a return type when an error occurs. Earlier, you can use false in union with other types, but now you can also use it as a standalone.

function alwaysFalse(): false
{
	return false;
}

The same is valid for true and null.

Disjunctive Normal Form (DNF) types

DNF is a standard way of organizing Booleans. We can apply DNF while declaring statements and write combined union and intersection types that the parser can handle. It is a powerful feature when used accurately.

Example:

// Accepts an object that implements both A and B,
// OR an object that implements D
(A&B)|D

Conclusion

It is a pre-release blog, and there might be some changes between now and the release. I hope that you will enjoy the new features.