Container

A container holds a list of elements and does not take care of keys.

Create a container

use Dustin\Encapsulation\Container;

$container = new Container();

A container can optionally be initialized with a list of elements:

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

Add elements

$container = new Container();

$container->add($foo, $bar);

You can pass as many elements as you want to the add-method.

Access Elements

You can get a single element of a container at a specific position:

$productNumbers = new Container(['My1003', 'My1004', 'My1005']);

$number = $productNumbers->getAt(1); // Returns 'My1004'

You also can get all elements of a container as array:

Count elements of a container

You can also check if a container has elements:

Iterate over all elements

You can also use a container in a loop and iterate over all elements:

Delete elements

You can clear a container which unsets all of it's elements:

Copy a container

Merging serveral containers together

$container will now be a new container object holding the values of $foo, $bar, $alice, $bob, $hello and $world.

You can pass as many container objects to the merge-function as you want.

Sorting elements

You can sort the elements of a container ascending, descending or by a callback. Internally the array functions usort, sort and rsort will be used so you optionally can pass their flags.

Sort elements by callback

Sort elements ascending

Sort elements descending

Array functions

The container class brings a bunch of wrapper methods according to some of PHP's array functions. Each function takes the same parameters as the default PHP function except the input array.

Most methods return the container itself or a new instance which makes it easy to concat method calls to get the wanted container object:

map will create and return a new container instance.

filter will create and return a new container instance.

slice will create and return a new container instance.

unique will create and return a new container instance.

replace will create and return a new container instance.

reverse will create and return a new container instance.

Last updated