Blog

Blog @template, template

All Articles(https://phpstan.org/blog)

Releases(https://phpstan.org/blog/releases)

Guides(https://phpstan.org/blog/guides)

Other(https://phpstan.org/blog/other)

Other Sections

RSS(https://phpstan.org/rss.xml)

Sponsor PHPStan!(https://phpstan.org/sponsor)

Generics in PHP using PHPDocs

December 2, 2019 · 23 min read

Generics is a really complex topic. It’s basically a programming language inside a programming language. But it’s also incredibly useful. I hope to introduce it pretty easily for you with a lot of examples so you can get a good idea of how generics work and how you can write your own generic code.

I gave a talk about this topic at IPC Munich 2023:

Also check out practical examples in the Generics By Examples(https://phpstan.org/blog/generics-by-examples) article.

Why generics? #

PHP itself doesn’t support generics natively. There was an RFC(https://wiki.php.net/rfc/generics) back in 2016 that didn’t go anywhere because it’s a really complicated thing to implement in the language runtime. If you want to learn more about the state of native generics in PHP, check out the PHP Foundation’s articles on the state of generics and collections(https://thephp.foundation/blog/2024/08/19/state-of-generics-and-collections/) and compile-time generics(https://thephp.foundation/blog/2025/08/05/compile-generics/).

If real generics were in PHP, they’d look something like this using native syntax:

class Entry < KeyType , ValueType > { // ... }

$entry = new Entry < int , string > ( 1 , 'test' ) ;

But this isn’t possible. The best we can do today is to use PHPDocs. And that’s where PHPStan comes in.

Without generics, if your function returns different types based on the argument types, you’d have to resort to returning a general type like object or mixed :

function findEntity ( string $className , int $id ) : ? object { // finds and returns an entity object based on $className // and primary key in $id }

This produces an unnecessarily wide return type. If you don’t use generics, you’ll probably find yourself getting errors like:

Call to an undefined method object::doSomething().

or:

Cannot access property $title on mixed.

Because you can’t safely call methods or access properties on object or mixed — you need a specific class name. On the other hand, if you use generics, your code will be more type-safe. Generics will make sure you have fewer false positives, and at the same time PHPStan will report more correct errors for you. It’s all about making types during static analysis more specific.

Infinite number of signatures #

The simplest explanation I came up with is that generics allow you to create an infinite number of signatures for your function. Imagine a function that returns the same type it receives — for integer it returns an integer, for string it returns a string. Without generics, we’d probably type it as accepting and returning mixed . But with generics, we can describe the exact relationship:

function foo ( $param ) { ... }

These types are set in stone. And that’s what generics are for. They offer generating an infinite number of signatures for functions and methods based on rules developers can define themselves.

Type variables #

These rules are defined using type variables. Other languages that have generics also use this term. In PHPDocs we annotate them with the @template tag. Consider a function that returns the same type it accepts:

function foo ( $a ) { return $a ; }

You introduce a type variable using @template and then you can use that identifier in your @param and @return tags. The type variable name can be anything — the convention is usually just a single uppercase letter, but it can be any identifier as long as you don’t use an existing class name.

How does this work in practice? For each call of a generic function, PHPStan looks at the parameters, tries to infer what the type variables are from the argument types, and then applies that knowledge to the return type.

You can also limit which types can be used in place of the type variable with an upper bound using the of keyword. This is called a “type variable bound”:

function foo ( $exception ) { ... }

Only objects of classes extending Exception will be accepted and returned by this function.

Default type #

Type variables can also have a default type using = . When type arguments have defaults, they don’t have to be specified when using the generic class:

class Pair { }

With the class above, these are all valid:

Pair — both T and U use their defaults ( string and int )

Pair<bool> — T is bool , U uses its default ( int )

Pair<bool, float> — both T and U are specified explicitly

Defaults can be combined with upper bounds: @template T of object = stdClass .

In some situations the @template-covariant PHPDoc tag can be used instead. Check out the guide on @template-covariant »(https://phpstan.org/blog/whats-up-with-template-covariant).

Class names #

If you want to involve a class name in the type resolution, you can use the class-string pseudotype for that:

function findEntity ( string $className , int $id ) { // ... }

If you then call findEntity(Article::class, 1) , PHPStan will know that you’re getting an Article object or null!

You can combine it however you want. Marking the return type as T[] (for example for a findAll() function) would infer the return type as an array of Articles:

function findAll ( string $className ) { // ... }

Generics can get pretty complicated. Here’s a little quiz — can you guess what built-in PHP function this signature describes?

function ?? ? ( $callback , $array ) { }

It’s array_map ! We need three type variables: K for the array key, V for the input value, and V2 for the output value. The callable transforms V to V2 , and the function returns an array with the same keys but the new value type. PHPStan uses this signature to check that the callback you pass in actually matches the array value type, and it correctly infers the return type.

Class-level generics #

Up until this point, I’ve written only about function-level or method-level generics. But a whole other area is type variables above classes. We can also make our classes generic by putting @template above a class or an interface:

interface Collection { }

Once a class has one or more template type variables, we call that class generic. We can then reference the type variable identifier in our methods and properties:

public function add ( $item ) : void ;

public function get ( int $index ) ;

The order matters — the first @template tag corresponds to the first position in the angle brackets, and so on for multiple templates.

The types of the Collection can be specified when you’re typehinting it somewhere else:

function foo ( Collection $dogs ) { // Dog expected, Cat given $dogs -> add ( new Cat ( ) ) ; }

When implementing a generic interface or extending a generic class, you have two options:

Specify the type variable of the interface/parent class. The child class will not be generic.

Preserve the genericness of the parent, the child class will also be generic.

Specifying the type variable is done with @extends , @implements , and @use tags — they match the corresponding PHP keywords:

class DogCollection implements Collection { }

Preserving the genericness is done by repeating the same @template tags above the child class and passing them through:

class PersistentCollection implements Collection { }

The same works for @extends when extending a class, and @use when using a trait:

trait FooTrait { ... }

class Foo {

use FooTrait ; }

“Does not specify its types” error #

One thing that people usually have problems with is that they try to use generic classes and PHPStan yells at them:

class HelloWorld { function sayHello ( ReflectionClass $r ) : void { }

Method HelloWorld::sayHello() has parameter $r with generic class ReflectionClass but does not specify its types: T

What does PHPStan want you to do? It wants you to add a PHPDoc that specifies what T is. ReflectionClass is a built-in PHP class, but PHPStan uses stub files(https://github.com/phpstan/phpstan-src/tree/2.2.x/stubs) to make some built-in classes generic because it’s really useful.

This is how the declaration of ReflectionClass looks like in PHPStan:

class ReflectionClass { ... }

You have several options how to fix the error:

If you just don’t care about generics in this situation and want to put something there, you can use the same thing that the template has as a bound. If the bound is object , use object . If the bound is missing, use mixed :

function sayHello ( ReflectionClass $r ) : void { }

Or you can say you accept reflections of only a certain class:

function sayHello ( ReflectionClass $r ) : void { }

Or maybe the most powerful option — you can make the function itself generic:

function sayHello ( ReflectionClass $r ) : object { return $r -> newInstance ( ) ; }

Now when you pass in a specific ReflectionClass when calling this method, PHPStan will extract what T is and use it as the return type.

The same applies when implementing generic interfaces. For example:

class Foo implements IteratorAggregate { }

Class Foo implements generic interface IteratorAggregate but does not specify its types: TKey, TValue