Categories

PHP 8.2 – What’s new, what changed and what is deprecated

PHP 8.2 is the latest major version that was released on December 08, 2022. PHP 8.2 brings up read only classes, true, false and null as stand alone types, deprecated dynamic properties for non anonymous classes etc.

So let’s explore the most important updates of PHP 8.2.

New read only classes

Until now, starting with PHP 8.1, we could define only readonly properties. So, if we didn’t want to change an instance of a class, we had to define every property as readonly. From PHP 8.2 we can define a class as readonly.

Example:

PHP 8.1

class Foo {
    public readonly string $name;
    public readonly int $age;

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

PHP 8.2

class readonly Foo {
    public string $name;
    public int $age;

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

Abstract or final classes can also be declared readonly. However, Interfaces and traits cannot be declared readonly.

Notice: Readonly classes can only contain typed properties. Declaring a property without a type will result in throwing an error. If you are not sure about what type should be assigned to a property, you can use mixed type.

Allow true, false and null as stand alone types

Until now, we couldn’t use true, false and null as stand alone types. We could use these types only in union types ( ex: string|null ).

Starting with PHP 8.2 we can use these types stand alone.

PHP < 8.2

class Foo {
    public function A(): bool {....}
    public function B(): bool {....}
    public function C(): string|null {....}
}

PHP 8.2

class Foo {
    public function A(): true {....}
    public function B(): false {....}
    public function C(): null {....}
}

Disjunctive Normal Form (DNF) Types

DNF is a standard of organizing boolean expressions. It represents a disjunction of conjunctions. Basically this means an OR and ANDs .

From PHP 8.2 we can use DNF when declaring types.

PHP < 8.2

class Foo {
    public function bar(mixed $entity) {
        if ((($entity instanceof A) && ($entity instanceof B)) || ($entity === null)) {
            return $entity;
        }

        throw new Exception('Invalid entity');
    }
}

PHP 8.2

class Foo {
    public function bar((A&B)|null $entity) {
        return $entity;
    }
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*