Readonly class feature in PHP 8.2

by

In PHP 8.2.0, a class can be marked with the readonly modifier. Creating a class as readonly will add the readonly modifier to the all declared attributes, and prevent the creation of dynamic properties. Also, it is not possible to add support for them by using the AllowDynamicProperties attribute. Trying to do so will trigger a compile-time error.

A readonly class can be extended only with a child class which is a readonly class.

Untyped and static properties cannot be marked with readonly modifier and cannot be declared in a readonly class

readonly class WebPortal
{
    public string $title;

    public string $description;

    public function __construct(string $title, string $description)
    {
        $this->title = $title;
        $this->description = $description;
    }
    
    public function get_title() {
        return $this->title;
    }
}

$obj = new WebPortal("GeekW3", "Thoughts of a passionate developer");
print $obj->get_title();    //Output: GeekW3

Leave a Reply

Your email address will not be published. Required fields are marked *