CKTIS / PHP
Attributes and reflection
An attribute attaches structured metadata to a declaration without invoking its constructor at the point of use.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
#[Attribute(Attribute::TARGET_METHOD)] class Label {}An attribute attaches structured metadata to a declaration without invoking its constructor at the point of use. Reflection retrieves attribute descriptors and constructor arguments. Calling newInstance() creates the attribute instance and checks applicability. Filter by the attribute class to avoid instantiating unrelated metadata.
#[Attribute(Attribute::TARGET_METHOD)] class Label{function __construct(public string $text){}}
class Report{#[Label("daily")] public function run(){}} $m=new ReflectionMethod(Report::class,"run");$d=$m->getAttributes(Label::class)[0];echo json_encode([$d->getArguments(),$d->newInstance()->text]);
[["daily"],"daily"]
Examples
<?php
#[Attribute(Attribute::TARGET_METHOD)] class Label{function __construct(public string $text){}}
class Report{#[Label("daily")] public function run(){}} $m=new ReflectionMethod(Report::class,"run");$d=$m->getAttributes(Label::class)[0];echo json_encode([$d->getArguments(),$d->newInstance()->text]);
Result
[["daily"],"daily"]