What will be the output of this PHP code using readonly properties?
<?php class User { public readonly string $name; public function __construct(string $name) { $this->name = $name; } } $user = new User("Alice"); echo $user->name; ?>
Readonly properties can be assigned once, usually in the constructor.
The readonly property $name is assigned in the constructor. Accessing it later prints the assigned value.
What happens when you try to modify a readonly property after the object is created?
<?php class Point { public readonly int $x; public function __construct(int $x) { $this->x = $x; } } $p = new Point(5); $p->x = 10; echo $p->x; ?>
Readonly properties cannot be changed after initial assignment.
Trying to assign a new value to a readonly property after construction causes a fatal error.
When can a readonly property be assigned a value in PHP?
Think about when readonly properties get their value safely.
Readonly properties must be assigned once, either directly when declared or inside the constructor. After that, they cannot be changed.
What error will this code produce?
<?php class Config { public readonly array $settings = []; public function addSetting(string $key, string $value): void { $this->settings[$key] = $value; } } $config = new Config(); $config->addSetting('theme', 'dark'); print_r($config->settings); ?>
Readonly means the property cannot be changed after initialization, including its contents.
Even though the array property is assigned an empty array at declaration, modifying its contents later is not allowed because the property is readonly.
Consider this code. What will be the output?
<?php class Address { public readonly string $city; public function __construct(string $city) { $this->city = $city; } } class Person { public readonly Address $address; public function __construct(Address $address) { $this->address = $address; } } $addr = new Address('Paris'); $person = new Person($addr); $person->address->city = 'London'; echo $person->address->city; ?>
Readonly applies to the property itself, but what about the object it points to?
The property $address in Person is readonly, so it cannot be reassigned. But the Address object itself is mutable unless its own properties are readonly. Here, city is readonly, so trying to change it causes a fatal error.