Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Generics

Generics, sometimes called parametered polymorphism, or more precisely parametric polymorphism, are a style of types, where the type of a property, parameter or return is specified at the declaration level.

The generics syntax looks like: $users = new List<User>(); where List is a class that holds a list of items, and those items are of the type between brackets. Here, it is User.

Generics allows the creation of general classes, that can process several types of data. The actual application’s type is declared in the type itself. This is similar to configure an array to only handle one type of elements.

Generics have been submitted as RFC since 2016, and are currently not implemented, in the foreseeable future.

One implementation of generics is available, with transpiling: see mrsuh/php-generics.

Generics are generally considered to be not supported, although external tools provide this feature, such as static analysis. Generics are not supported at the engine level.

Documentation

See Also