How to start using generic types in PHP

Click for: original source

Generic types are templates which allow us to write the code without specifying a particular type of data on which the code will work. Thanks to them, we avoid the redundancy and the objects operate on the previously declared types. By Jarek Szutkowski.

A good example here are collections of various types. If we want to be sure that a collection consists of a given data type, we can either create a separate class to store each type, use various types of assertions, or just use generic types. In case of separate collection classes we create redundancy - we duplicate classes that differ only in the type of stored object. In case of assertions, the IDE will not be able to tell us the syntax. Only generic types will allow us to create one class that will guarantee data consistency and correct IDE autocompleting.

The article content is split into these bits:

  • How to deal with generic types in PHP
  • Examples
  • Extending templates
  • Guessing object by class name
  • Multiple generic types
  • Generic types in callback functions
  • Code analysis from the command line

Although the PHP is developing quite dynamically, it does not support native generic types, which are widely used in languages such as Java or C#. Fortunately, there are many tools that allow us to imitate these types, and thus, extend the capabilities of the language. Nice one!

[Read More]

Tags php web-development app-development learning