Since PHP 8.2, classes can be declared as readonly. This means that all class properties automatically becomes readonly. The readonly properties were introduced in PHP 8.1. These properties can be initialized once and cannot be modified later. Readonly classes are declared with readonly
keyword.
Let's say we have User
class, which has two readonly properties.
<?php
class User
{
private readonly string $firstName;
private readonly string $lastName;
public function setName(string $firstName, string $lastName): void
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
Since PHP 8.2, class can be rewritten by making it as readonly.
<?php
readonly class User
{
private string $firstName;
private string $lastName;
public function setName(string $firstName, string $lastName): void
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
For demonstration purpose, we created an instance of User
class. A second call of setName
method produces a fatal error because firstName
property already set.
<?php
require_once 'User.php';
$user = new User();
$user->setName('John', 'Anderson'); // OK
$user->setName('Alex', 'Smith'); // Error
There are some notes for readonly classes.
Readonly abstract and final classes
Abstract classes and final classes can also be declared as readonly. The order of the keywords does not matter.
<?php
abstract readonly class Animal {} // OK
<?php
final readonly class SiberianHusky {} // OK
Readonly subclasses
If parent class is declared as readonly then child class must be declared as readonly as well.
<?php
readonly class Dog {}
<?php
readonly class Pomsky extends Dog {} // OK
<?php
class AlaskanMalamute extends Dog {} // Error
Leave a Comment
Cancel reply