Download the PHP package jausions/php-typed-collections without Composer
On this page you can find all versions of the php package jausions/php-typed-collections. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jausions/php-typed-collections
More information about jausions/php-typed-collections
Files in jausions/php-typed-collections
Package php-typed-collections
Short Description Collections and arrays with type constraint.
License MIT
Informations about the package php-typed-collections
Typed Collections
Type hinting is evolving but PHP 7 still does not currently provide a way to define the type of the elements of an array.
This library provides traits that can be used to implement type checking.
If you do not wish to implement anything, simply use one of the prebuilt solutions below:
- For Doctrine collections, see this package: jausions/php-typed-doctrine-collections.
For the purpose of this library, the term type is used loosely to refer to built-in PHP types, classes, and even application-domain types.
Installation
In the examples below, the require 'vendor/autoload.php';
is implied.
Simplistic Example
This example only implements the ArrayAccess PHP Predefined Interface.
This means no foreach
iteration, count()
, and so on...
Type Defined by a Sample Value
The element validation is done against the type of a sample value.
Type Defined by a Closure
The elements added to the collection can be checked with a closure:
Type Defined by a Class Name
Objects added to the collection can be checked against a class name:
Built-In Library Types
Apart from a closure or a class name, the setElementType()
method also
accepts the following predefined values:
array
boolean
callable
double
integer
number
json
object
resource
string
Checking a Value
If you want to know if a value would be accepted in the typed collection,
you can use the isElementType()
method.
Custom Type Collections
You can easily create collections by extending the base class or by including the trait into your own implementation of the ArrayAccess interface.
Remarks:
- We could have type hinted the
enter()
method with theCar
class instead of theVehicle
class. This would also have thrown a \TypeError exception. - I am aware that I mixed the types in the docBlock and the signature of
the
getCars()
method. It is somewhat more legible and may help your IDE. However, the benefit may vary depending on your editor / IDE, and it may lead to confusion if trying to use some array function that expect a nativearray
type.