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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dustinsimon.gitbook.io/encapsulation/getting-started/advanced/immutable-encapsulations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
