PHP Attributes

Add structured, compile-time metadata to classes, methods, and properties.

PHP 8 Attributes replace PHPDoc annotations (like @Route) with first-class structured metadata that can be inspected at runtime via the Reflection API.

Key Takeaways: PHP Attributes

Mastering PHP Attributes helps you write clean and reliable PHP code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

PHP Attributes Code Example

PHP
#[Attribute]
class Route {
    public function __construct(public string $path) {}
}

class ApiController {
    #[Route("/api/v1/users")]
    public function list() {}
}

$ref = new ReflectionMethod(ApiController::class, "list");
$attr = $ref->getAttributes(Route::class)[0]->newInstance();
echo $attr->path;
Output
/api/v1/users
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services