Web Development Handbook

Web Development Handbook

Development is fun in a funny way

PHP 8.2: Readonly Classes
PHP

PHP 8.2: Readonly Classes

0 votes
0 votes
0 comments
275 views
Share

By Nihar Ranjan Das, Published on May 17th 2023 | 6 mins, 591 words

Recently, PHP 8.2, a significant update to PHP, was released. It has a ton of unique features, and the read-only classes are the finest. Now, a class can be defined as read-only. When a class is defined as read-only, all of its attributes also become read-only. 

Prior to PHP 8.2, each read-only property had to be defined separately. Here are some illustrations.

Rather than making this right:

class Role
{
    public function __construct(
        public readonly string $title,
        public readonly Status $status
    ) {}
}

We can now declare this:

readonly class Role
{
    public function __construct(
        public string $title,
        public Status $status
    ) {}
}


Readonly properties in PHP have certain rules. Let's explore these rules in detail.

  • Readonly properties can only be initialized once. Once a value is assigned to a readonly property, it cannot be changed.
  • Readonly properties must have a type declaration. If a type is not specified, it will result in a fatal error.
  • Readonly properties should not have a default value, unless the class is using promoted properties. Default values are not allowed for standalone readonly properties.
  • The value of a readonly property cannot be unset. Once a value is assigned, it remains constant throughout the program execution.

These rules also apply to readonly classes. Readonly classes follow the same guidelines as readonly properties.


Initialized Once

We can initialize the properties of readonly classes anywhere inside our class. But if we set the value, it can't be changed next.

readonly class Role {
    public function __construct(public string $title) {}
}

$role = new Role('Admin');
$role->title = 'User';


// Error: Cannot modify readonly property Role::$title

We created a Role class instance and set it to the $role variable in the code above. The error message shows that it is not permitted to edit the Role::$title property. The error occurs when we try to modify the read-only property directly in the following line.

Unsetting readonly class property

Unsetting readonly class property is not possible after initialization.

readonly class Role {
    public function __construct(public string $title) {}
}

$role = new Role('Admin');

unset($role->title);

// Error: Cannot unset readonly property Role::$title in ...:...

In this example, a new Role object is created with the title 'Admin'. Since the $title property is readonly. An attempt to unset the $title property using the unset() function results in an error, indicating that unsetting a readonly property is not allowed.

No dynamic properties

Readonly classes don’t support dynamic properties. So if you want to add the #[AllowDynamicProperties] attribute, it will through a compile-time error.

#[\AllowDynamicProperties]
readonly class Role {
}

// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo


Static properties not supported

Readonly class can't be static cause static properties are marked as readonly modifier.

readonly class Role
{
    public static bool $active;
}

// Fatal error: Readonly class Role cannot declare static properties

This code snippet demonstrates the attempt to declare a static property in a readonly class. In this example, the $active property is declared as a static property. A fatal error happens when the code is attempted to run. The error message clearly indicates that a readonly class cannot declare static properties.

Untyped property not supported

Readonly classes don't support untyped properties. All the properties of readonly class must need to be typed.

readonly class Role
{
    public $active;
}

// Fatal error: Readonly property Role::$active must have type

This code snippet demonstrates the usage of a readonly class with a property that lacks a specified type declaration. In this example, the $active property is declared without a specified type. A fatal error happens when the code is attempted to run. The error message indicates that a readonly property must have a type declaration.


If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.