Generics in PHP
16 September 2025 (Updated 16 September 2025)
On this page
Example 1: A simple generic Collection
class
Define the generic class (note the use of @template TItem
):
<?php
/**
* @template TItem
*/
final readonly class Collection
{
/**
* @param array<int, TItem> $items
*/
public function __construct(private array $items) {}
/**
* @return array<int, TItem>
*/
public function all(): array
{
return $this->items;
}
}
Use the class:
<?php
$names = new Collection(['Bob' ,'Jim', 'Mike', 'Alice']);
$names = $names->all();
foreach($names as $index => $name) {
echo strtolower($name) . PHP_EOL;
}

Example 2
<?php
declare(strict_types=1);
namespace App\Repository;
use App\Entity\User;
use App\Exception\EntityNotFoundException;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
/**
* @template TEntity of object
* @extends ServiceEntityRepository<TEntity>
*/
class BaseRepository extends ServiceEntityRepository
{
/**
* @return TEntity
* @throws EntityNotFoundException
*/
public function findOrFail(int $id)
{
$user = $this->find($id);
if (!$user) {
throw new EntityNotFoundException(User::class, $id);
}
return $user;
}
/**
* @return TEntity|null
*/
public function findFirst()
{
return $this->createQueryBuilder('o')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
}
Tagged:
PHP