Advertisement
Intermediate PHP, Type Declarations & Strict Types

What are readonly properties in PHP, and how do they help you create objects whose internal state cannot be accidentally changed after they are first constructed?

Short answer

A readonly property, once initialized, typically within a class's constructor, can never be modified again afterward, and attempting to reassign a readonly property's value anywhere else in the code will immediately raise an error, which is particularly useful for creating…

Save PHP mock interview
Advertisement
AModel answer
A readonly property, once initialized, typically within a class's constructor, can never be modified again afterward, and attempting to reassign a readonly property's value anywhere else in the code will immediately raise an error, which is particularly useful for creating objects that represent an immutable value, meaning a value that should never change once created, such as a Money object representing a specific fixed monetary amount, or a data transfer object representing a snapshot of information at one specific point in time.
class Money {
    public function __construct(
        public readonly int $amountInCents,
        public readonly string $currency,
    ) {}
}
Real-world example
A Money class marks both its amount and currency properties as readonly, guaranteeing that once a specific Money object is created representing a transaction amount, that value can never be accidentally altered elsewhere in the application later.
Likely follow-ups
  • What happens if you try to modify a readonly property after it has already been initialized?
  • Can a readonly property hold a mutable object, and if so, can that inner object's own properties still be changed?
Related topics