0
0
PHPprogramming~5 mins

Readonly classes in PHP

Choose your learning style9 modes available
Introduction

Readonly classes help keep data safe by making sure once you set values, they cannot be changed later.

When you want to create objects that hold fixed information, like a person's ID or a product code.
When you want to avoid accidental changes to important data in your program.
When you want to make your code easier to understand by showing which data should never change.
Syntax
PHP
readonly class ClassName {
    public function __construct(
        public Type $property1,
        public Type $property2
    ) {}
}

The readonly keyword before class means all properties are readonly.

You must set all properties when creating the object, usually in the constructor.

Examples
This example creates a readonly class User with two properties. Once set, they cannot be changed.
PHP
<?php
readonly class User {
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

$user = new User("Alice", 30);
echo $user->name . " is " . $user->age . " years old.";
This example shows a readonly class Point for fixed coordinates.
PHP
<?php
readonly class Point {
    public function __construct(
        public float $x,
        public float $y
    ) {}
}

$point = new Point(1.5, 2.5);
echo "Point coordinates: (" . $point->x . ", " . $point->y . ")";
Sample Program

This program creates a readonly class Book with title and author. It prints the book details. Trying to change the title after creation will cause an error.

PHP
<?php
readonly class Book {
    public function __construct(
        public string $title,
        public string $author
    ) {}
}

$book = new Book("1984", "George Orwell");
echo "Book: " . $book->title . " by " . $book->author . "\n";

// Trying to change a property will cause an error
// $book->title = "Animal Farm"; // This will fail
OutputSuccess
Important Notes

Readonly classes were introduced in PHP 8.2.

Once an object of a readonly class is created, you cannot change its properties.

This helps prevent bugs caused by unexpected data changes.

Summary

Readonly classes make all properties unchangeable after creation.

They are useful for fixed data that should not be modified.

Trying to change a readonly property will cause an error.