Generics in PHP: Why They Are Needed and How to Use Them 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

\n\n

In the world of modern PHP development, more and more attention is being paid to strict typing and code safety. One of the most powerful tools introduced in PHP 8.0 is Generics (generic types). If you are a beginner in PHP and are hearing this term for the first time — don't be afraid. In this article, we will explain in simple terms what Generics are, why they are needed, and how to use them in practice.

\n\n

Imagine a situation: you are writing a function that should work with different data types — numbers, strings, objects. Without generics, you would have to either use mixed (which reduces safety) or write separate functions for each type. Generics solve this problem elegantly and efficiently.

\n\n

In this article, we will cover:

\n
    \n
  • What Generics are and their main advantages
  • \n
  • How to declare generic classes and functions
  • \n
  • Real-world examples of use in projects
  • \n
  • Common beginner mistakes and how to avoid them
  • \n
\n\n

What are Generics and Why Are They Needed?

\n\n

The Problem Without Generics

\n\n

Suppose you are creating a class for working with a collection of elements. Without generics, you would have to use the mixed type or write specialized classes for each data type:

\n\n
<?php\n// Bad approach — using mixed\nclass Collection {\n    private array $items = [];\n\n    public function add(mixed $item): void {\n        $this->items[] = $item;\n    }\n\n    public function get(int $index): mixed {\n        return $this->items[$index] ?? null;\n    }\n}\n\n// Now you can accidentally add a string to a number collection\n$numbers = new Collection();\n$numbers->add(42);\n$numbers->add('string'); // No error will occur, but the logic is broken\n?>
\n\n

This code works, but it is unsafe. You don't know what data types are stored in the collection, and you could get a runtime error.

\n\n

The Solution with Generics

\n\n

Generics allow you to specify which data types your class, function, or interface will work with. The syntax resembles angle brackets <T>, where T is a placeholder for a specific type:

\n\n
<?php\n// Good approach — using Generics\nclass Collection<T> {\n    private array $items = [];\n\n    public function add(T $item): void {\n        $this->items[] = $item;\n    }\n\n    public function get(int $index): ?T {\n        return $this->items[$index] ?? null;\n    }\n}\n\n// Now PHP will check the types\n$numbers = new Collection<int>();\n$numbers->add(42);\n// $numbers->add('string'); // Fatal error: Uncaught TypeError\n?>
\n\n

Now the PHP compiler knows that the $numbers collection can only contain integers. Any attempt to add a string will cause an error at development time.

\n\n

Main Advantages of Generics

\n\n
    \n
  • Type Safety — errors are detected at compile time, not at runtime.
  • \n
  • Code Readability — it is immediately clear what types a function or class works with.
  • \n
  • Reduced Duplication — one generic class replaces dozens of specialized ones.
  • \n
  • Improved IDE Support — autocompletion and hints work correctly.
  • \n
\n\n

How to Use Generics in PHP: Practical Examples

\n\n

1. Generic Classes

\n\n

The most common scenario is creating collections, stacks, queues, and other data structures. Let's look at an example of a stack:

\n\n
<?php\nclass Stack<T> {\n    private array $stack = [];\n\n    public function push(T $item): void {\n        $this->stack[] = $item;\n    }\n\n    public function pop(): ?T {\n        return array_pop($this->stack);\n    }\n\n    public function isEmpty(): bool {\n        return empty($this->stack);\                

Blogs

Book Recommendations