CKTIS / PHP
Attributi e reflection
Un attributo associa metadati a una dichiarazione senza eseguire il costruttore nel punto d’uso.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
#[Attribute(Attribute::TARGET_METHOD)] class Label {}Un attributo associa metadati a una dichiarazione senza eseguire il costruttore nel punto d’uso. La reflection legge descrittori e argomenti. newInstance() crea l’istanza e controlla la destinazione. Filtrare per classe evita di istanziare metadati estranei.
#[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"]
Esempi
<?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]);
Risultato
[["daily"],"daily"]