31.6 C
Monday, June 24, 2024

PHP 8.2 is released with read-only classes, new stand-alone types, trait constants, and more

With read-only classes, new stand-alone types, a new random extension, trait constants, and more, the PHP team has released PHP 8.2 today:

classes that are read-only

Extending the functionality of PHP 8.1’s read-only properties, class marking makes all of a class’s properties read-only and stops new dynamic properties from being created.

readonly class BlogData
    public string $title;
    public Status $status;
    public function __construct(string $title, Status $status)
        $this->title = $title;
        $this->status = $status;

Types of disjunctive normal forms (DNF)

Union and intersection types are combined in DNF types:

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

Three stand-alone types: null, false, and true

The standalone types false, true, and null are now supported in PHP 8.2. This illustration should be fairly clear:

class Falsy
    public function alwaysFalse(): false { /* ... */ *}
    public function alwaysTrue(): true { /* ... */ *}
    public function alwaysNull(): null { /* ... */ *}

Consistencies in characteristics

Traits can now contain constants. Constants cannot be accessed by the trait name; instead, they must be accessed through the class using the trait:

trait Foo
    public const CONSTANT = 1;
    public function bar(): int
        return self::CONSTANT; // Fatal error
class Bar
    use Foo;
var_dump(Bar::CONSTANT); // 1

Decreasing dynamic property value

When you assign a value to a dynamic property, you will receive a deprecation notice because dynamic properties are deprecated:

class User
    public $name;
$user = new User();
$user->last_name = 'Doe'; // Deprecated notice
$user = new stdClass();
$user->last_name = 'Doe'; // Still allowed

Using the AllowDynamicProperties attribute, you can also choose to allow dynamic properties:

class User() {}
$user = new User();
$user->foo = 'bar';

New functions, attributes, interfaces, and classes

New classes, interfaces, attributes, and functions are included in PHP 8.2. Visit the New Classes, Interfaces, and Functions section of the to see the full list. PHP 8.2.0 Release Announcement.

The attribute AllowDynamicProperties has already been discussed. An additional attribute that redacts sensitive data in a stack trace is #[\SensitiveParameter]:

function sensitiveParametersWithAttribute(
    string $secret,
    string $normal
) {
    throw new Exception('Error!');

Related Articles


Please enter your comment!
Please enter your name here

Latest Articles