> For the complete documentation index, see [llms.txt](https://dustinsimon.gitbook.io/encapsulation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dustinsimon.gitbook.io/encapsulation/getting-started/advanced/immutable-encapsulations.md).

# 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.

```php
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.

```php
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:

```php
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.

```php
use Dustin\Encapsulation\ImmutableContainer;

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

$container->add('Hello world'); // Will throw an exception
```
