Posted by Kosal
Since PHP 8.0, attributes have brought native support for metadata in a clean, efficient, and type-safe way. Attributes allow you to add structured, machine-readable annotations directly to your classes, methods, functions, parameters, and more.
If you're coming from frameworks like Laravel or Symfony, or have used PHPDoc annotations before, you'll find PHP attributes a more robust and modern alternative.
In this article, we’ll cover:
Attributes in PHP are a way to add metadata to code using native syntax. Before PHP 8, developers relied on PHPDoc comments (e.g., @Route
, @ORM\Entity
) to provide this information. Now, with attributes, you can annotate your code in a more structured and IDE-friendly way.
#[MyAttribute]
class MyClass {}
This is much cleaner and integrates with PHP’s reflection system for better performance and easier parsing.
To define a custom attribute, you use the #[Attribute]
class from the global namespace.
use Attribute;
#[Attribute]
class Route {
public function __construct(
public string $path,
public string $method = 'GET'
) {}
}
Now you can use this attribute on a controller method:
#[Route('/home', method: 'GET')]
function home() {
return 'Welcome Home!';
}
You can retrieve attributes using PHP's Reflection API:
$refFunc = new ReflectionFunction('home');
$attributes = $refFunc->getAttributes(Route::class);
foreach ($attributes as $attribute) {
$route = $attribute->newInstance();
echo $route->path; // Outputs: /home
}
Here are a few ways attributes can be used in real-world projects:
#[Route('/users', method: 'POST')]
function createUser() {}
#[Length(min: 5, max: 20)]
public string $username;
#[RequiresPermission('admin')]
function deleteUser() {}
#[Entity]
#[Table(name: 'users')]
class User {
#[Column(type: 'int')]
public int $id;
}
Feature | PHP Attributes | PHPDoc Annotations |
---|---|---|
Native Support | ✅ Yes | ❌ No |
Type Safety | ✅ Strong | ❌ Weak |
Reflection Ready | ✅ Yes | ❌ No |
IDE Support | ✅ Growing | ✅ Mature |
Performance | ✅ Fast | ❌ Slower (requires parsing comments) |
Attributes are a game-changer in modern PHP development. They bring clarity, structure, and performance to metadata handling in PHP applications. As more frameworks adopt them (Symfony, Laravel, etc.), attributes are becoming the new standard for handling everything from routing to validation and beyond.
If you're starting a new project in PHP 8+, embrace attributes—they make your code cleaner and more maintainable.