← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 17 of 24

PHP Attributes

What are Attributes?

Attributes, introduced in PHP 8.0, let you attach structured metadata directly to classes, methods, and properties in native PHP syntax, replacing what used to require parsing PHPDoc comments as plain text.

Example: What are Attributes?

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

#[Route('/home')]
class HomeController {}

echo "Attributes attach structured metadata directly in PHP syntax";
?>

Defining custom Attributes

Defining a custom attribute is just defining a normal class and marking it with the built-in #[Attribute] annotation, which tells PHP this class is meant to be used as metadata rather than instantiated directly in the usual way.

Example: Defining custom Attributes

php
<?php
#[Attribute]
class Deprecated {
    public function __construct(public string $reason = '') {}
}
echo "Deprecated is now usable as an attribute";
?>

Applying Attributes

Applying an attribute means writing #[YourAttribute] directly above the class, method, or property it describes -- the syntax is compact and lives right alongside the code it annotates.

Example: Applying Attributes

php
<?php
#[Attribute]
class Deprecated {
    public function __construct(public string $reason = '') {}
}

class Report {
    #[Deprecated('Use generate() instead')]
    function oldGenerate() {}
}
echo "Attribute applied directly above the method";
?>

Reading Attributes with Reflection

Attributes are inert until read: the Reflection API's getAttributes() method retrieves them at runtime, which is how frameworks use attributes to drive behavior like route registration or validation rules.

Example: Reading Attributes with Reflection

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

#[Route('/home')]
class HomeController {}

$reflection = new ReflectionClass(HomeController::class);
$attributes = $reflection->getAttributes(Route::class);
echo $attributes[0]->newInstance()->path;
?>

Attributes vs. PHPDoc

Because attributes are parsed and validated by the PHP engine itself rather than by a separate documentation-comment parser, they're both faster to read and far less prone to silent typos than PHPDoc annotations.

Example: Attributes vs. PHPDoc

php
<?php
// PHPDoc (parsed as a comment, not validated by PHP):
// /** @route /home */

// Attribute (parsed and validated by the engine itself):
#[Attribute]
class Route {
    public function __construct(public string $path) {}
}
echo "Attributes are engine-native, PHPDoc is just a comment convention";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.