Skip to content
Advertisement

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

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 ExtensionExtension
 *
 * @param class-string<T> $id
 *
 * @throws ContainerExceptionInterface
 * @throws ExtensionExtensionNotFound
 *
 * @return T
 */

Advertisement

Answer

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 ExtensionExtension. 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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement