Attributes

An attribute is a note the engine stores on a declaration. In PHP it is written with hash and square brackets above a class, method, property or parameter, and reflection reads it back when the code needs the value.

#[...] syntax

An attribute is structured metadata placed right above a class, method, property, or parameter. It replaces doc comment annotations with syntax the engine understands. See also attributes in PHP 8.0.

Start with a plain class for the attribute, then apply it with hash and brackets.

<?php #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] class UserController { } #[Route("/api/posts")] class PostController { } $ref = new ReflectionClass(PostController::class); echo $ref->getAttributes()[0]->newInstance()->path, PHP_EOL;

php syntax.php

/api/posts

Arguments follow normal call syntax, including named arguments and arrays. Applying an attribute never runs code by itself, it only stores metadata. The path appears only when the reflection object builds the instance.

Read them with reflection

Reflection reads attributes at runtime. Ask a reflection object for its attributes, filter by class name, then create an instance to get the stored values.

This pattern powers routers, validators, and test runners.

<?php #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] class UserController { } $ref = new ReflectionClass(UserController::class); foreach ($ref->getAttributes(Route::class) as $attr) { $route = $attr->newInstance(); echo $route->path, PHP_EOL; }

php read.php

/api/users

The filter by class name skips every other attribute of the declaration, and the loop stays short when a class carries more than one. A router reads the same value and turns it into a table of paths and handlers.

Built-in attributes

PHP ships a small set of engine attributes. They mark overrides, silence deprecations during internal migrations, and hide sensitive values from stack traces.

Learn these four first, then check the manual for version specific additions.

<?php class TokenStore implements Countable { #[ReturnTypeWillChange] public function count(): int { return 0; } public function login( string $name, #[SensitiveParameter] string $password ): bool { return $name !== "" && $password !== ""; } } $store = new TokenStore(); var_dump($store->login("ada", "secret")); var_dump($store->login("ada", "")); var_dump(count($store));

php builtin.php

bool(true)
bool(false)
int(0)

Override checks that a method really overrides a parent method. Deprecated marks your own API as scheduled for removal. SensitiveParameter keeps the password out of a stack trace, and ReturnTypeWillChange tells the engine that the return type of an internal interface method is deliberately left alone. The three result lines come from var_dump(), which prints the type next to the value.

When attributes pay off

Use attributes when one declaration must serve both code and configuration. Routing, validation rules, serialization names, and access policies are classic cases.

Skip them for plain business logic. A normal method call is easier to debug than hidden metadata.

<?php #[Attribute(Attribute::TARGET_FUNCTION)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] function listUsers(): array { return []; } $fn = new ReflectionFunction("listUsers"); foreach ($fn->getAttributes(Route::class) as $attr) { echo $attr->newInstance()->path, PHP_EOL; }

php when.php

/api/users

A function carries attributes as a class does, and the target in the declaration is what allows it. The same attribute on the wrong kind of declaration is refused when the instance is built, not when the file loads.

Exercises

  1. Add a second argument to Route with a default value and read it in the loop.
  2. Apply two different attributes to one class and filter the loop for one of them.
  3. Mark a method of a child class with #[Override] and rename the parent method. What does PHP report?
  4. Put #[Route("/x")] on a function although the declaration names only TARGET_CLASS, and print what the catch says.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an attribute?

    Answer

    Metadata attached to a declaration that the engine stores

    The attribute is part of the compiled declaration, and code reads it through reflection.

  2. What happens when the file with an attribute loads?

    Answer

    Nothing: the metadata is stored and no code runs

    Applying an attribute only records it; the constructor runs when reflection calls newInstance().

  3. How does code read the attributes of a class?

    Answer

    With ReflectionClass::getAttributes()

    The reflection object lists the attributes, and newInstance() on one returns the object with its values.

  4. Which built-in attribute asks the engine to check that a method overrides its parent?

    Answer

    #[Override]

    Override reports a method that claims to override something the parent does not declare.

  5. What does this program print? <?php #[Attribute(Attribute::TARGET_CLASS)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] class UserController { } #[Route("/api/posts")] class PostController { } $ref = new ReflectionClass(PostController::class); echo $ref->getAttributes()[0]->newInstance()->path;

    Answer

    /api/posts

    The reflection object looks at PostController, so it builds the attribute with the posts path.

  6. What does this program print? <?php #[Attribute(Attribute::TARGET_CLASS)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] class UserController { } $ref = new ReflectionClass(UserController::class); foreach ($ref->getAttributes(Route::class) as $attr) { $route = $attr->newInstance(); echo $route->path; }

    Answer

    /api/users

    The loop builds the stored attribute of the class and prints the path given to it.

  7. What does this program print? <?php class TokenStore { public function login( string $name, #[SensitiveParameter] string $password ): bool { return $name !== "" && $password !== ""; } } $store = new TokenStore(); var_dump($store->login("ada", ""));

    Answer

    bool(false)

    The empty password fails the condition, so the method returns false.

  8. What does this program print? <?php #[Attribute(Attribute::TARGET_FUNCTION)] class Route { public function __construct(public string $path) { } } #[Route("/api/users")] function listUsers(): array { return []; } $fn = new ReflectionFunction("listUsers"); foreach ($fn->getAttributes(Route::class) as $attr) { echo $attr->newInstance()->path; }

    Answer

    /api/users

    The target allows a function, so the reflection reads the path the attribute stored.

  9. What does this program print? <?php #[Attribute(Attribute::TARGET_CLASS)] class Route { public function __construct(public string $path) { } } class Controller { #[Route("/x")] public function index(): void { } } $ref = new ReflectionMethod(Controller::class, "index"); try { $ref->getAttributes()[0]->newInstance(); } catch (Error $e) { echo "refused"; }

    Answer

    refused

    The attribute allows only classes, so building it on a method throws an Error that the catch prints.

  10. What does this program print? <?php class Route { public function __construct(public string $path) { } } #[Route("/x")] class Controller { } $ref = new ReflectionClass(Controller::class); try { $ref->getAttributes()[0]->newInstance(); } catch (Error $e) { echo "not an attribute"; }

    Answer

    not an attribute

    A class without the #[Attribute] marker is not an attribute, so newInstance() refuses it.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev