Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

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 Jun 9 by avibootz
edited Jun 9 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 Jun 9 by avibootz
...