PHP code example of aziule / typed-collections

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

    

aziule / typed-collections example snippets


public function ($elements); // Too vague

/**
* @param array $ips
*/
public function (array $ips); // Still too vague (can be associative, contain objects, etc.)

/**
* @param MyObject[] $objects
*/
public function (array $objects); // Best practice

Aziule\TypedCollections\ArrayCollection;
Aziule\TypedCollections\BooleanCollection;
Aziule\TypedCollections\DoubleCollection;
Aziule\TypedCollections\IntCollection;
Aziule\TypedCollections\StringCollection;

use Aziule\TypedCollections\IntCollection;

$collection = new IntCollection(); // Empty at that stage
$collection[] = 42;

foreach ($collection as $item) {
    // ...
}

use Aziule\TypedCollections\StringCollection;

$collection = new StringCollection([
    'my',
    'collection',
    'of',
    'strings',
]);

echo count($collection); // 4

use Aziule\TypedCollections\ObjectCollection;

class MyObject {
    // ...
}

$collection = new ObjectCollection(MyObject::class); // The collection is of type MyObject
$collection[] = new MyObject();
$collection[] = new \DateTime(); // Will throw an InvalidItemTypeException

use Aziule\TypedCollections\ObjectCollection;

class MyObject {
    // ...
}

$collection = new ObjectCollection(MyObject::class, [
    new MyObject(),
    new MyObject(),
]);

echo count($collection); // 2

use Aziule\TypedCollections\ObjectCollection;

$collection = new ObjectCollection(\stdClass::class);
echo $collection->getClass(); // 'stdClass'

use \Aziule\TypedCollections\ObjectCollection;

class Item
{
    private $value;

    public function __construct($value)
    {
        $this->value = $value;
    }
}

class ItemCollection extends ObjectCollection
{
    public function __construct(array $items = [])
    {
        parent::__construct(Item::class, $items);
    }
}

$collection = new ItemCollection();
$collection[] = new Item('Foo');
$collection[] = new Item('Bar');

// And then use this collection
public function doSomething(ItemCollection $itemCollection)
{
    // ...
}