Encapsulation
v2.0
v2.0
  • dustin/encapsulation
  • Getting started
    • Basics
      • Container
    • Advanced
      • Object maps
      • Immutable encapsulations
    • Objects with properties
    • Intersection calculation
Powered by GitBook
On this page
  • Immutable ArrayEncapsulation
  • Immutability in your own encapsulation
  • Immutable containers
  1. Getting started
  2. Advanced

Immutable encapsulations

Sometimes it's necessary to prevent changing data of an encapsulation. Immutable encapsulations must be initialized with data in their constructor. Afterwards data cannot be changed.

Immutable ArrayEncapsulation

Immutable ArrayEncapsulations can hold any data without restriction.

use Dustin\Encapsulation\ImmutableEncapsulation;

$encapsulation = new ImmutableEncapsulation([
    'foo' => 'bar',
    'hello' => 'world'
]);

$encapsulation->set('field', 'value'); // Will throw an exception

Immutability in your own encapsulation

Each encapsulation class you create on your own can be immutable regardless wether it's an ArrayEncapsulation or a PropertyEncapsulation or something else.

use Dustin\Encapsulation\PropertyEncapsulation;
use Dustin\Encapsulation\ImmutableTrait;

class MyEncapsulation extends PropertyEncapsulation {
    
    use ImmutableTrait;
    
    protected $foo = null;
    
    protected $bar = null;
}

$encapsulation = new MyEncapsulation(['foo' => 'foo']);

$encapsulation->set('bar', 'bar'); // Will throw an exception

Each encapsulation inheriting from AbstractEncapsulation can be checked about their mutability:

use Dustin\Encapsulation\Encapsulation;

$encapsulation = new Encapsulation(['foo' => 'foo']);
$myEncapsulation = new MyEncapsulation(['foo' => 'foo', 'bar' => 'bar']);

$encapsulation->isMutable(); // Returns true
$myEncapsulation->isMutable(); // Returns false

Immutable containers

There is also a class of an immutable container which prevents changing it's elements.

use Dustin\Encapsulation\ImmutableContainer;

$container = new ImmutableContainer(['foo', 'bar']);

$container->add('Hello world'); // Will throw an exception
PreviousObject mapsNextObjects with properties

Last updated 1 year ago