PHP
Reading annotations
Learn to read doc comments and #[] attributes with reflection.
PHP 8 attributes and getAttributes
PHP 8 attributes add metadata to classes, methods and properties. The syntax is #[Route("/users")]; it looks like a call inside square brackets.
Reflection reads these attributes. getAttributes() returns an array of ReflectionAttribute. newInstance() instantiates the attribute class with its constructor arguments.
So a #[Route] tag on a method becomes a real Route object.
Defining and reading an attribute class
To define an attribute class, mark it with #[Attribute]. Constructor parameters shape the data the attribute carries.
$attrs = $rm->getAttributes(); gives you the array. $attrs[0]->newInstance() builds the Route object; then you read the value via ->path.
Old-style doc-block comments are still read with getDocComment(); but attributes are type-safe and structured.
Exercise Print the #[Route] attribute of list
The UserController::list method below is marked with #[Route("/users")]. Build a ReflectionMethod instance and print each attribute's name on a separate line using getAttributes().
Show example solution
Build $rm = new ReflectionMethod("UserController", "list");. Print with foreach ($rm->getAttributes() as $attr) { echo $attr->getName() . "\n"; }.
Example solution:
<?php
#[Attribute]
class Route {
public function __construct(public string $path) {}
}
class UserController {
#[Route("/users")]
public function list(): array {
return [];
}
}
$rm = new ReflectionMethod("UserController", "list");
foreach ($rm->getAttributes() as $attr) {
echo $attr->getName() . "\n";
}
Test yourself
-
Match attribute concepts
- #[Route]
- PHP 8 attribute syntax
- getAttributes
- Returns the attribute list
- newInstance
- Instantiates the attribute class
- getDocComment
- Returns the doc-block comment
-
What does getAttributes() return?
- An array of strings
- An array of ReflectionAttribute
- An array of ReflectionMethod
- A single ReflectionAttribute object
Show answer
An array of ReflectionAttribute — Correct. You get one ReflectionAttribute per attribute.
-
Loop with getAttributes()
<?php
$rm = new ReflectionMethod("UserController", "list");
foreach ($rm->____() as $attr) {
echo $attr->getName() . "\n";
}
Show answer
<?php
$rm = new ReflectionMethod("UserController", "list");
foreach ($rm->getAttributes() as $attr) {
echo $attr->getName() . "\n";
}
Next lesson: Dynamic method invocation