Generics in PHP: Why They Are Needed and How to Use for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Generics in PHP: What They Are and Why They Are Needed



If you are just starting to learn PHP or have been writing in it for some time, you have likely encountered a situation where a function or class needs to work with different data types. For example, you create a collection that can store numbers, strings, and objects. Without Generics, you either have to write separate classes for each type or use mixed types, which reduces code safety.



Generics are a mechanism that allows you to create classes, interfaces, and functions that work with various data types while maintaining strict typing. Support for Generics in PHP appeared starting with version 8.0, and was significantly improved in PHP 8.1 and 8.2. In this article, we will break down why they are needed, how to use them, and what advantages they provide.



Why Are Generics Needed in PHP?



The Problem of Missing Generic Types

Imagine you are writing a class for working with a list of elements. Without Generics, you would have to use the mixed type or write separate classes for each data type:



<?php// Without Generics — unsafeclass SimpleList {    private array $items = [];

public function add($item): void { $this->items[] = $item; }

public function get(int $index): mixed { return $this->items[$index] ?? null; }}

// Usage$list = new SimpleList();$list->add(42);$list->add('string'); // No error will occur, but logic is broken$value = $list->get(0); // Type mixed — IDE won't hint that it's int?>


As you can see, this approach leads to potential errors: you might accidentally add a string where only numbers are expected, and the IDE will not be able to warn you about it.



Advantages of Generics

  • Type safety: the compiler and IDE check type compliance at the code writing stage.
  • Reusability: one class or function works with any data types.
  • Code readability: it is immediately clear which types are expected.
  • Fewer errors: accidental type mismatches are eliminated.


With Generics, the same list class becomes safe and universal:



<?php// With Generics — safeclass GenericList {    private array $items = [];

public function add(T $item): void { $this->items[] = $item; }

public function get(int $index): ?T { return $this->items[$index] ?? null; }}

// Usage$intList = new GenericList();$intList->add(42);// $intList->add('string'); // Type error!

$stringList = new GenericList();$stringList->add('Hello');$value = $stringList->get(0); // IDE knows this is string?>


How to Use Generics in PHP



Basic Syntax

Generics in PHP are declared using angle brackets <> and the letter T (for Type) — this is the conventional name for a type variable. You can use any names, but T is the standard.



Example with a class:

<?phpclass Container {    private T $value;

public function __construct(T $value) { $this->value = $value; }

public function getValue(): T { return $this->value; }}

$intContainer = new Container(100);$stringContainer = new Container('Hello');?>


Type Constraints

Sometimes you need the type parameter to conform to a specific interface or class. For this, bounds are used:



<?phpinterface Printable {    public function print(): string;}

class Document implements Printable { public function print(): string { return 'Document'; }

Blogs

Book Recommendations