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;- 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