Download the PHP package grikdotnet/generics without Composer
On this page you can find all versions of the php package grikdotnet/generics. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package generics
Generics in PHP
- Story of generics in PHP
- Why do you need generics programming
- How to use this package
- Syntax
- System requirements and compatibility
- Solution diagrams
- Performance impact
Why do you need generics?
Generic programming is an algorithm where data types are declared as "to-be-specified-later", when needed.
It allows writing much less code, and have data types checked by the PHP engine in data sets.
Data may have unexpected structure, especially when it is obtained from databases, APIs, and 3rd party code. For single-value variables we define parameter types, but for the composite types such as array, ArrayObject, SplFixedArray one cannot define types of values in runtime. To define data types for values we could create multiple classes with the same code, where the only difference would be a type of a parameter. E.g.
This feels wrong, and violates the "Don't repeat yourself" principle.
Generics allow defining types of parameters when you create an instance, with just one short clause. And yet you have just one class declaration for all types you need.
How to use
- Add the package as a dependency for Composer, as usually:
composer require grikdotnet\generics. - Call
new \grikdotnet\generics\Enable();in bootstrap to enable the class loader. - Declare a wildcard class.
Using the trait is optional. It provides a convenient shortcut method T() to create concrete types:
That's it. Now PHP will check the type of values added to the ArrayObject instance, and trigger a TypeError when the type does not match.
Now let's use the typed Collection as a parameter type in a method:
This way data types of elements are checked by the PHP engine, and we can avoid writing a lot of type checks in a loop over data sets in every method.
Find more about syntax in the documentation.
All versions of generics with dependencies
ext-tokenizer Version *
ext-ctype Version *
ext-mbstring Version *
ext-zend-opcache Version *
composer-runtime-api Version *
nikic/php-parser Version ^5.4