PHP code example of dcsg / php-immutable-collections

1. Go to this page and download the library: Download dcsg/php-immutable-collections library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dcsg / php-immutable-collections example snippets


 declare(strict_types=1);

use DCSG\ImmutableCollections\ImmutableCollection;

final class MyStringCollection extends ImmutableCollection {
    protected function validateItems(array $elements): void
    {
        foreach ($elements as $element) {
            if (!\is_string($element)) {
                throw new InvalidArgumentException('Element is not a String.');
            }
        }
    }
}

$collection = MyStringCollection::create(['foo', 'bar']);
echo $collection->count(); // 2
$slicedCollection = $collection->slice(0, 1); // MyStringCollection { $elements=['foo']}

 declare(strict_types=1);

use DCSG\ImmutableCollections\SetImmutableCollection;

final class MyStringSetCollection extends SetImmutableCollection {
    protected function validateItems(array $elements): void
    {
        foreach ($elements as $element) {
            if (!\is_string($element)) {
                throw new InvalidArgumentException('Element is not a String.');
            }
        }
    }
}

$collection = MyStringSetCollection::create(['foo', 'bar']);
echo $collection->count(); // 2
$slicedCollection = $collection->tail(); // MyStringSetCollection { $elements=['bar']}

$collection = MyStringSetCollection::create(['foo', 'bar', 'foo']); // Throws InvalidArgumentException
bash
composer