CKTIS / PHP
Attributen en reflectie
Een attribuut koppelt metadata aan een declaratie zonder ter plekke de constructor aan te roepen.
Versie: PHP 8.4; repository runtime, production runtime not attested
Syntax
#[Attribute(Attribute::TARGET_METHOD)] class Label {}Een attribuut koppelt metadata aan een declaratie zonder ter plekke de constructor aan te roepen. Reflectie leest descriptoren en argumenten. newInstance() maakt de instantie en controleert het doel. Filter op attribuutklasse om andere metadata over te slaan.
#[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"]
Voorbeelden
<?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]);
Resultaat
[["daily"],"daily"]