Part 2 · Types / Generics
Lesson 5 of 8

Generics

Classes, interfaces, traits, functions, and methods take compile-time generic parameters. They are checked by the compiler and erased into PHPDoc that PHPStan and your IDE understand:

Box.ppphp
class Box<T>
{
    public function __construct(private T $value) {}
}

Press Build PHP to read the emitted PHP and its @template tags. Then try changing the instantiation to hold an int:

Box.ppphp
Box<int> $box = new Box(42);

Nothing is reified: operations that need a type parameter at runtime, like new T(), are rejected at compile time.