PHPackages                             esemve/typed-collection - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. esemve/typed-collection

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

esemve/typed-collection
=======================

Create typed collections in PHP

v1.0.5(8y ago)0614MITPHP

Since Feb 19Pushed 8y ago1 watchersCompare

[ Source](https://github.com/esemve/TypedCollection)[ Packagist](https://packagist.org/packages/esemve/typed-collection)[ RSS](/packages/esemve-typed-collection/feed)WikiDiscussions master Synced yesterday

READMEChangelog (5)Dependencies (2)Versions (6)Used By (0)

Typed Collections
=================

[](#typed-collections)

You like Laravel Collections, but you don't use Laravel? You've used the Collections, but you feel like something missing? Like type hints? It's your package!

### The problem

[](#the-problem)

From PHP 7.0 you can typehint many things in php functions. Like:

```
function hello(string $name): string {
   return sprintf('Hello %s!', $name);
}
```

But what if you want a string list? You can't typehint the content of arrays, you can only hint the array:

```
function hello(array $names): array;
```

And not like this:

```
function hello(array[string] $names): array[string];
```

It's sad.

### The solution

[](#the-solution)

If you use this package, you can use type hinted Collections instead of simple arrays. Like this:

```
$names = new StringCollection(['Pete', 'Steve', 'John']);

function hello(StringCollection $names): StringCollection {
 ...
}
```

It's so simple!

Installation
------------

[](#installation)

```
composer require esemve/typed-collection

```

### Types

[](#types)

You can use these default types:

- ArrayCollection
- BooleanCollection
- CallableCollection
- ClassCollection
- FloatCollection
- IntegerCollection
- NullCollection
- ObjectCollection
- ResourceCollection
- StringCollection

### Create your own typed collection

[](#create-your-own-typed-collection)

If you want create your own typed collection, just create a new Collection file, and extend the AbstractTypedCollection. After this your only task is to fill the isValid function. It will check every added value, and if you try to add a value that is not allowed, the AbstractTypedCollection will automatically throw an InvalidTypedException.

```
/// PostCollection.php:
