phpfn/immutable

Simple helper to ensure immutable objects

Installs: 7 696

Dependents: 0

Suggesters: 0

Security: 0

Stars: 9

Watchers: 1

Forks: 1

pkg:composer/phpfn/immutable

2.0.1 2020-11-22 21:15 UTC

This package is auto-updated.

Last update: 2025-09-23 08:21:46 UTC


README

Installation

Library can be installed into any PHP application:

$ composer require phpfn/immutable

In order to access library make sure to include vendor/autoload.php in your file.

<?php

require __DIR__ . '/vendor/autoload.php';

Usage

To ensure immunity of objects, you just need to wrap any code of your method in a closure.

Mutable object example:

class Example
{
    private int $value = 42;

    public function update(int $newValue): self
    {
        $this->value = $newValue;
    
        return $this;
    }
}

Making it immutable:

class Example
{
    private int $value = 42;

    // Sample #1 (PHP 7.4+)
    public function with(int $newValue): self
    {
        return immutable(fn () => $this->value = $newValue);
    }
}

That`s all!