Value objects are immutable objects that represent a set of values. They are used to encapsulate data and behavior, and are often used in domain-driven design.
Characteristics of Value Objects:
- Immutable (cannot be changed once created)
- Equal by value (not by reference)
- No identity (no unique ID)
- Can be used as array keys or hash map keys
Mutability:
Mutability refers to the ability of an object to change its state after creation.
Types of Mutability:
- Mutable: Can change state after creation (e.g., arrays, objects with setters)
- Immutable: Cannot change state after creation (e.g., value objects, strings)
Best Practices:
- Use immutable objects when possible (e.g., value objects, data transfer objects)
- Use mutable objects when necessary (e.g., entities, domain objects)
- Avoid mixing mutable and immutable objects in the same class
<?php
class Money {
private $amount;
private $currency;
public function __construct($amount, $currency) {
$this->amount = $amount;
$this->currency = $currency;
}
public function getAmount() {
return $this->amount;
}
public function getCurrency() {
return $this->currency;
}
public function equals(Money $other) {
return $this->amount === $other->amount && $this->currency === $other->currency;
}
}
Benefits of Immutable Objects:
- Thread-safety
- Easy to reason about and test
- Can be used as cache keys or hash map keys
- Reduces side effects and bugs
By using value objects and controlling mutability, we can write more predictable, maintainable, and scalable code in PHP OOP.
Top comments (0)