Readonly Classes in PHP 8.2

TheDevick,New in PHP 8.2

Marking a class as readonly will add the readonly modifier to every declared property

In PHP 8.1 (opens in a new tab), the developers team of PHP added the Readonly Properties (opens in a new tab), which is a way to protect the properties, blocking any modification in his value after the Initialization.

class Client
{
  public function __construct(
    public readonly string $name,
    public readonly string $email
  )
  {
  }
}
 
$client = new Client("Erick", "email@domain.com");
 
$client->name = "TheDevick";    // This isn't allowed because the properties are readonly
$client->email = "other@mail.com" // This isn't allowed because the properties are readonly

It's cool, isn't it? But we can see that all the properties in the Client class are readonly. Then, in PHP 8.2, you can say that a class is readonly, and all the declared properties will be readonly. Let's check:

readonly class Client
{
  public function __construct(
    public string $name,
    public string $email
  )
  {
  }
}
 
$client = new Client("Erick", "email@domain.com");
 
$client->name = "TheDevick";       // This isn't allowed because the class are readonly
$client->email = "other@mail.com"; // This isn't allowed because the class are readonly

Note that, in this example, we use the Constructor property promotion (opens in a new tab), a feature added in PHP 8.0 (opens in a new tab)

Sources ✨

© Erick Bilhalba Abella.