PHP 8
Advanced
OOP
· 6 min read
PHP Attributes
Lesson 40 of 43 in the PHP 8 learning path.
How do I attach metadata to a class without a comment parser?
An attribute is a class attached to code with #[Name]. Reflection reads it at runtime.
Docblocks are comments. Attributes are real code the engine can see.
Syntax & Parameters
#[RequiresTrack('php')]
Example
<?php
declare(strict_types=1);
#[Attribute(Attribute::TARGET_METHOD)]
final class RequiresTrack
{
public function __construct(public string $track) {}
}
final class Catalog
{
#[RequiresTrack('php')]
public function show(): void {}
}
$method = new ReflectionMethod(Catalog::class, 'show');
$attrs = $method->getAttributes(RequiresTrack::class);
$track = $attrs[0]->newInstance()->track;
echo $track, PHP_EOL;
Expected Output
php
Line-by-Line Walkthrough
- RequiresTrack is an attribute class.
- TARGET_METHOD limits where it may be placed.
- The constructor stores the track name.
- Catalog::show is marked with php.
- ReflectionMethod finds the method.
- getAttributes filters to this attribute class.
- newInstance builds the attribute object.
- The script prints php.
Common Pitfalls & Security
Know the failure before you copy it.
- Forgetting #[Attribute] on the class makes the marker illegal.
- newInstance runs the constructor. A bad argument throws.
- Attributes are not inherited unless you ask reflection to look at the parent.
- They are not a substitute for a policy. They only describe the code.
Best Practices & Modern Standards
Use attributes for framework metadata you will reflect on.
Keep the attribute class small and typed.
Real-World Use
A tiny router reads RequiresTrack from an action and refuses a request whose lesson track does not match, before the action runs.
Frequently Asked Questions
Are attributes comments?
No. They are classes the engine stores on the target.
When are they constructed?
When you call newInstance, not when the file loads.
Can they target a class?
Yes. Set TARGET_CLASS or combine flags.
Do they replace interfaces?
No. An interface is a type. An attribute is metadata.