Generics in PHP
Simulate generic types in PHP using PHPDoc annotations (@template), understand their IDE and static-analysis benefits with tools like PHPStan.
What Are Generics?
Generics allow you to write a single class or function that works correctly with multiple types while keeping full type safety. Languages like Java, C#, and Go have built-in generic syntax. PHP does not have runtime generics, but you can simulate them fully through PHPDoc `@template` annotations — understood by static analysis tools like PHPStan and Psalm, and by IDEs like PhpStorm.
1. The Problem Generics Solve
Reuse logic across types without losing type information.
2. How PHP Simulates Generics
@template PHPDoc annotation — zero runtime cost, full static analysis.
Generic Classes with @template
The `@template` tag on a class definition creates a type placeholder that flows through all methods annotated with it.
1. Typed Collection
A list that only accepts one type of item.
2. Multiple Type Parameters
Use two @template tags for key-value pairs.
3. Generic Stack
Classic stack data structure with full type safety.
Generic Functions with @template
The `@template` tag on a function or method links the types of parameters and return values without losing specificity.
1. Identity Function
Return exactly what was passed in — same type.
2. first() — Extract from Array
Return the first element with its element type preserved.
3. Generic map() Function
Transform array elements while preserving type information.
Constrained Templates (@template T of ...)
Use `@template T of SomeType` to require that `T` extends or implements a specific class or interface. This lets you call methods on `T` inside the generic code.
1. @template T of ClassName
Constrain T to a specific type or interface.
2. Generic Repository Pattern
A typed repository base class constrained to a model type.
Generic Interfaces
Interfaces can also carry `@template` annotations, letting implementing classes bind the type parameter.
1. @template on Interfaces
Define a contract that is agnostic of the concrete type.
Generics with PHPStan
PHPStan is the most popular PHP static analysis tool. It reads `@template` annotations and enforces generic constraints at analysis time — catching bugs that PHP itself would only catch at runtime, if at all.
1. Installing PHPStan
Add PHPStan to your project via Composer.
2. Common PHPStan Generic Errors
Understand what PHPStan catches.
3. phpstan.neon Configuration
Configure PHPStan for your project.
Best Practices
PHPDoc generics add significant value in library and framework code. Use them where they reduce duplication and improve IDE assistance — but do not over-annotate simple code.
1. When to Use @template
High-value scenarios for generic annotations.
2. Covariance & Invariance in PHP Generics
PHPDoc generics are invariant by default.
3. Contravariance (@template-contravariant)
Write-only containers — accept a base type where a derived type is expected.