Start · Sprachen · PHP · Kapitel · Attributes (PHP 8.0+)
// Kapitel · PHP

Attributes (PHP 8.0+)

Attributes sind strukturierte Metadaten für Klassen, Methoden und Properties. Sie ersetzen DocBlock-Annotationen.

Attributes stehen in eckigen Klammern mit #[Attribute]-Syntax und werden per Reflection ausgelesen:

Ein einfaches Attribute definieren

#[\Attribute(\Attribute::TARGET_METHOD)]
class Route
{
    public function __construct(
        public string $method,
        public string $path,
    ) {}
}

Verwendung an einer Methode

class UserController
{
    #[Route(method: 'GET', path: '/users')]
    public function index(): array
    {
        return User::all();
    }

    #[Route(method: 'POST', path: '/users')]
    public function store(array $data): User
    {
        return User::create($data);
    }
}

Attribute per Reflection auslesen

$reflection = new ReflectionClass(UserController::class);

foreach ($reflection->getMethods() as $method) {
    foreach ($method->getAttributes(Route::class) as $attr) {
        $route = $attr->newInstance();
        echo "{$route->method} {$route->path} → {$method->name}\n";
    }
}

// GET /users → index
// POST /users → store

Praxisbeispiele in freier Wildbahn: Symfony Routing, Doctrine ORM, PHPUnit-Test-Attribute (#[Test], #[DataProvider]), Laravel Route Attributes.