// Immutable User Class in PHP (Enforce Immutability)
/*
In PHP, immutability is enforced by:
- Making properties private
- Assigning them ONLY in the constructor
- Providing ONLY getters (no setters)
- Avoiding any method that changes internal state
*/
final class User
{
// Private properties → cannot be modified outside the class
private int $id;
private string $name;
// Constructor initializes values exactly once
public function __construct(int $id, string $name){
$this->id = $id;
$this->name = $name;
}
// Read‑only accessors (getters)
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
// No setters → immutability enforced
}
// Main program
$u = new User(42, "Alfred");
echo "ID: " . $u->getId() . PHP_EOL;
echo "Name: " . $u->getName() . PHP_EOL;
// The following lines would cause errors:
// $u->id = 100; // ERROR: Cannot access private property
// $u->name = "Abbi"; // ERROR: Cannot access private property
// $u->setName("Abbi"); // ERROR: No setter exists - Call to undefined method User::setName()
/*
run:
ID: 42
Name: Alfred
*/