Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

Why did I got that error?

like image 763
Tommy Hoang Avatar asked Sep 13 '25 06:09

Tommy Hoang


1 Answers

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);
    }
}
like image 188
Dharman Avatar answered Sep 15 '25 20:09

Dharman