Codectionary / Developer documentation / PHP

PHP attributes as metadata

PHP 8 attributes attach structured metadata to declarations. The metadata has no automatic behavior; reflection or a framework must read it and decide what to do.

Syntax

#[Attribute(Attribute::TARGET_CLASS)] class Label { /* ... */ }

Examples

PHP attributes as metadata

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
#[Attribute(Attribute::TARGET_CLASS)]
class Label {
    public function __construct(public string $text) {}
}
#[Label('Reports')]
class ReportController {}
$metadata = (new ReflectionClass(ReportController::class))->getAttributes(Label::class);
echo $metadata[0]->newInstance()->text, PHP_EOL;
  1. Output: Reports. newInstance constructs the attribute object using the declaration arguments.

Best practices

  • Restrict attribute targets and treat constructors as executable code. Do not instantiate arbitrary metadata without considering its origin.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading