Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot instantiate a read-only class which extends another read-only class in PHP?

This is my class hierarchy:

readonly class ParentClass {
    public function __construct(
        public string $lastName
    ){
    }
}

readonly class ChildClass extends ParentClass {
    public function __construct(
        public string $firstName,
        public string $lastName
    ){
        parent::__construct($lastName);
    }
}

$child = new ChildClass('John', 'Doe');

I got an exception with message that "Cannot modify readonly property ParentClass::$lastName".

I’ve read many articles or answers of questions in Stackoverflow but nobody talked about this case or I didn’t find out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why did I got that error?

>Solution :

You are trying to redefine the property in the child class. You can’t do that.

Define the property only in the parent class.

readonly class ParentClass {
    public function __construct(
        public string $lastName
    ){
    }
}

readonly class ChildClass extends ParentClass {
    public function __construct(
        public string $firstName,
        string $lastName // No promoted property here. 
    ){
        parent::__construct($lastName);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading