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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With