What does the annotation @template mean in PHP doc blocks?
Asked Answered
E

1

10

I could see this PHPDoc block in the FakerPHP/Faker package, and I'm not aware what does @template mean? you can find it in the package's main branch on this line

/**
 * @template T of Extension\Extension
 *
 * @param class-string<T> $id
 *
 * @throws ContainerExceptionInterface
 * @throws Extension\ExtensionNotFound
 *
 * @return T
 */
Epifocal answered 21/10, 2021 at 21:11 Comment(0)
E
11

The @template annotation relates to a concept called Generics, which does not currently exist in PHP, but are a way of dynamically describing the contents of a parameter or return type that would be unknown until a class is instantiated or method called.

For PHP specifically, here is an article describing the doc blocks themselves and how to use them.

For the code you referenced, the template specifies T will be an instance of Extension\Extension. The $id parameter will be the class name for T, and @return says the method will return an instance of T.

Using the method would be something like $faker->ext(MyExtension::class), which would return an instance of MyExtension.

If you want to follow the rabbit, here is more on Generic Programming.

Enosis answered 21/10, 2021 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.