Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

New features of PHP 8.2 in Code Blocks

The release of PHP’s latest version, PHP 8.2, is just around the corner. On December 8, 2022 to be precise.

In this article, I’m going to list all the new features that are going to be introduced in PHP 8.2 in form of code blocks. This way, you can easily copy and paste the code blocks and try them out in your local environment.

This won’t include improvements and bug fixes that come with PHP 8.2. I’m only going to cover the ones that I think are worth mentioning. So, let’s get started.

Readonly Classes

Readonly classes are just regular classes prepended by the readonly modifier. This feature is in line with the readonly properties that were introduced in PHP 8.1.

readonly class Book 
{
    public function __construct(
        public string $author,
        public string $title,
    ) {}
}

$book = new Book('Ruskin Bond', 'Maharani');

$book->author = 'J. K. Rowling';
// Error: Cannot modify readonly property Book::$author

The true type

The true type is a new type that can be used to specify that a variable can only be assigned a boolean value of true.

function enableFeature(true $feature): true
{
    // do something

    return true;
}

enableFeature(false);

// PHP Fatal error:  Uncaught TypeError: enableFeature(): 
// Argument #1 ($feature) must be of type true, bool given

The false and null types

The false and null types are new types that can be used to specify that a variable can only be assigned a boolean value of false or null respectively.

function disableFeature(false $feature): true
{
    // do something

    return true;
}

disableFeature(true);
// PHP Fatal error:  Uncaught TypeError: disableFeature(): 
// Argument #1 ($feature) must be of type false, bool given,

And here’s an example of the null type:

class Nil
{
    public null $nil = null;
 
    public function isNull(null $nil): true 
    { 
        /* ... */ 

        return true;
    }
}

$nil = new Nil();
$nil->isNull(true);

// PHP Fatal error:  Uncaught TypeError: Nil::isNull(): 
// Argument #1 ($nil) must be of type null, bool given

Using constants in traits

PHP 8.2 will allow you to use constants in traits. This means that you can now define constants in traits, and they can be used in classes that use the trait as well as in the trait itself.

trait PersonTrait
{
    public const MIN_AGE = 18;

    public function isAdult(): bool
    {
        return $this->age >= self::MIN_AGE;
    }
}

class Person
{
    use PersonTrait;

    private int $age;

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

echo Person::MIN_AGE;
// Output: 18

$person = new Person(20);

echo $person->isAdult();
// Output: true

Disjunctive Normal Form (DNF) types

PHP 8.2 will introduce a new type called DNF (Disjunctive Normal Form). This type is a combination of the | and & operators. It allows you to specify a type that is the union of two or more types, and each of those types is the intersection of one or more other types.

interface User
{
    public function getName(): string;
}

interface Admin
{
    public function getName(): string;
}

interface SuperAdmin
{
    public function getName(): string;
}

function fetchUserName((Admin&SuperAdmin)|User $user): string
{
    return $user->getName();
}

$user = new class implements Admin {
    public function getName(): string
    {
        return 'User';
    }
};

fetchUserName($user);
// PHP Fatal error:  Uncaught TypeError: fetchUserName(): 
// Argument #1 ($user) must be of type (Admin&SuperAdmin)|User, Admin@anonymous given

New Random Extension

PHP 8.2 will introduce a new random API that will replace the existing mt_rand() and rand() functions. The new API will be based on a single Randomizer class which provides various randomization methods (like get int/bytes, shuffle string/arrays).

$is_production = false;
$rng = $is_production
    ? new Random\Engine\Secure()
    : new Random\Engine\PCG64(1234);
 
$randomizer = new Random\Randomizer($rng);
$randomizer->shuffleString('jhondoe');
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?