Hari 27: Immutability & Value Objects
55 min
Last updated 09 Apr 2026
Value Objects
readonly class Money {
public function __construct(
public readonly int $amount, // dalam sen
public readonly string $currency,
) {}
public function tambah(Money $other): self {
if ($this->currency !== $other->currency) {
throw new \InvalidArgumentException("Currency berbeda!");
}
return new self($this->amount + $other->amount, $this->currency);
}
public function kurang(Money $other): self {
return new self($this->amount - $other->amount, $this->currency);
}
public function format(): string {
return number_format($this->amount / 100, 2) . " " . $this->currency;
}
public function equals(Money $other): bool {
return $this->amount === $other->amount && $this->currency === $other->currency;
}
}
$harga = new Money(50000, "IDR");
$diskon = new Money(5000, "IDR");
$final = $harga->kurang($diskon);
echo $final->format() . "\n"; // 450.00 IDR
💡
Notice: 212°F = 100°C dan 300K = 26.85°C. Value objects tidak mutable — operasi selalu return instance baru.
Assignment
Buat readonly class Suhu dengan property $nilai dan $satuan (C/F/K). Tambahkan method keCelsius(): float (konversi ke Celsius) dan __toString() yang return "$nilai°$satuan". Buat objek 212°F dan 300°K, tampilkan hasil keCelsius() keduanya.
Expected output:
100.00
26.85
PHP
index.php
Solution
Output