How to enforce immutability to prevent the modification of values in PHP

2 Answers

0 votes
// 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

*/

 



answered 12 hours ago by avibootz
edited 12 hours ago by avibootz
0 votes
// immutable values

const X = 10;       // compile‑time constant
define("Y", 20);    // runtime constant

echo X . "\n";
echo Y . "\n";

// X = 99;   // Parse error: syntax error, unexpected token "="
// Y = 99;   // Parse error: syntax error, unexpected token "="



/* 
run:

10
20

*/

 



answered 12 hours ago by avibootz
...