Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Immutable

An immutable object, exhibiting immutability, is an object that can’t be changed. It may be created, read and cloned. On the other hand, a mutable object may change when one of its method is called, even if this is not visible from the outside.

Immutable objects are thread-safe.

Immutable objects often return a clone version of themselves, after modification.

<?php

    class Elephpant {
        private $age = 0;

        function inc() : self {
            $return = clone $this;
            $return->age +=1;

            return $return;
        }
    }

    $elephpant = new elephpant();
    $olderElephpant = $elephpant->inc();

    // $elephpant and $olderElephpant are two distinct objects

?>

Documentation

See Also