Attributes #[] Replacing Docblock Annotations
TL;DR
PHP 8.0 native attributes (#[Route('/home')]) replace fragile DocBlock @annotations — they're syntactically valid, parseable without reflection hacks, and supported by IDEs and static analysis.
Explanation
PHP 8.0 attributes: #[Attribute] on the attribute class, #[Route('/home')] on the target. Read with Reflection: (new ReflectionClass($obj))->getAttributes(Route::class). Benefits over DocBlocks: syntactically valid PHP (checked at parse time), no regex parsing, IDE completion, static analysis support, can be classes with validation. Built-in attributes: #[Override] (8.3), #[AllowDynamicProperties] (8.2), #[Deprecated] (8.4), #[ReturnTypeWillChange], #[SensitiveParameter] (8.2). Frameworks (Symfony, Laravel) have migrated from DocBlock annotations to native attributes.
Common Misconception
✗ DocBlock annotations and PHP attributes are parsed the same way — DocBlocks are strings read with Reflection::getDocComment() + regex. Attributes are first-class PHP structures.
Why It Matters
Native attributes replace fragile string parsing with proper PHP syntax — eliminating annotation parsing bugs and enabling IDE autocompletion on metadata.
Common Mistakes
- Using #[] syntax in PHP < 8.0 — fatal syntax error.
- Not declaring the #[Attribute] marker on custom attribute classes.
- Using attributes without reading them via Reflection — they have no effect at runtime on their own.
Code Examples
✗ Vulnerable
/**
* @Route('/home', methods={'GET'})
* @IsGranted('ROLE_USER')
*/
class HomeController {} // Parsed with fragile regex
✓ Fixed
#[Route('/home', methods: ['GET'])]
#[IsGranted('ROLE_USER')]
class HomeController {}
// Reading attributes:
$attrs = (new \ReflectionClass(HomeController::class))
->getAttributes(Route::class);
foreach ($attrs as $attr) {
$route = $attr->newInstance();
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
24
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
Amazonbot 8
Unknown AI 4
Perplexity 4
ChatGPT 1
Google 1
Meta AI 1
Ahrefs 1
Bing 1
Also referenced
How they use it
crawler 19
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Medium
⚡ Quick Fix
Migrate framework DocBlock annotations to native #[] attributes. Add #[Attribute] to custom annotation classes. Use named args in complex attribute constructors.
📦 Applies To
PHP 8.0+
web
cli
queue-worker
Symfony
Laravel
🔍 Detection Hints
#\[
Auto-detectable:
✗ No
phpstan
psalm
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: Medium
Context: Class