CKTIS / PHP
Atribúty a reflexia
Atribút pripojí metadáta k deklarácii bez volania konštruktora na mieste použitia.
Verzia: PHP 8.4; repository runtime, production runtime not attested
Syntax
#[Attribute(Attribute::TARGET_METHOD)] class Label {}Atribút pripojí metadáta k deklarácii bez volania konštruktora na mieste použitia. Reflexia načíta opisovače a argumenty. Až newInstance() vytvorí inštanciu a overí cieľ. Výber triedy atribútu zabráni vytvoreniu nesúvisiacich metadát.
#[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"]
Príklady
<?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]);
Výsledok
[["daily"],"daily"]