🐘 PHP Advanced

What is immutability and value objects in PHP?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

Answer

Immutable objects cannot be changed after creation — every "modification" returns a new object with the changed state. In PHP, implement with readonly properties (PHP 8.1) or by returning new instances from methods: public function withCurrency(string $currency): static { return new static($this->amount, $currency); }. Value Objects are immutable objects defined entirely by their values (not an identity/ID) — two Money objects with the same amount and currency are equal. Common value objects: Money, Email, Address, DateRange, Color. Benefits: thread safety, predictable behavior (no side effects), easy to test, and can be safely shared. PHP 8.1 readonly classes make immutable value objects trivial: readonly class Money { public function __construct(public int $amount, public string $currency) {} }.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a PHP codebase.