PHP code example of lc5 / typed-collection

1. Go to this page and download the library: Download lc5/typed-collection 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/ */

    

lc5 / typed-collection example snippets


use Lc5\TypedCollection\AbstractTypedCollection;
use Lc5\TypedCollection\Exception\UnexpectedValueException;

class stdClassCollection extends AbstractTypedCollection
{
    public function getType(): string
    {
        return \stdClass::class; //can be any class or internal type
    }
}

$collection = new stdClassCollection([new \stdClass(), new \stdClass()]);
$collection[] = new \stdClass();

try {
    $collection[] = 'invalid';
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed.
}

try {
    $collection = new stdClassCollection(['invalid', new \stdClass()]);
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed.
}


use Lc5\TypedCollection\TypedArray;
use Lc5\TypedCollection\Exception\UnexpectedValueException;

$values = [new \stdClass(), new \stdClass()];

$typedCollection = new TypedCollection(\stdClass::class, $values);
$typedCollection[] = new \stdClass();

try {
    $typedCollection[] = 'invalid';
} catch (UnexpectedValueException $e) {
    echo $e->getMessage(); //Invalid value type: string. Only \stdClass is allowed.
}