Sobes.tech
Middle

Does having a public property in a class mean that the class is immutable?

sobes.tech AI

Answer from AI

No.

A public property in a class means that the value of this property can be changed from outside the object. An immutable object is one whose state (the values of its properties) cannot be changed after creation. Having a public property contradicts the principle of immutability.

To achieve immutability, a class must meet the following conditions:

  • All properties should be private or protected.
  • There should be no setters (methods that change property values).
  • All dependencies (objects that this class works with) should also be immutable or their state should not change from outside.
  • The constructor should fully initialize the object, and it should not be changed after creation.
  • If changes are needed, new instances of the object should be created with new values.

Example of a class with a public property (mutable):

<?php
class MutableObject
{
    public $value; // Public property

    public function __construct($value)
    {
        $this->value = $value;
    }
}

$obj = new MutableObject(10);
echo $obj->value; // 10

$obj->value = 20; // Value changed from outside
echo $obj->value; // 20

Example of an immutable class implementation:

<?php
class ImmutableObject
{
    private $value; // Private property

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function getValue() : int
    {
        return $this->value;
    }

    // Method for "changing" the value, actually creates a new object
    public function withValue(int $newValue) : self
    {
        return new self($newValue);
    }
}

$obj1 = new ImmutableObject(10);
echo $obj1->getValue(); // 10

// $obj1->value = 20; // Error: Cannot access private property ImmutableObject::$value

$obj2 = $obj1->withValue(20); // Creates a new object
echo $obj1->getValue(); // 10 (original object unchanged)
echo $obj2->getValue(); // 20 (new object with changed value)
Does having a public property in a class mean that… - sobes.tech