CKTIS / PHP
Attribute und Reflection
Ein Attribut hängt Metadaten an eine Deklaration, ohne dort den Konstruktor auszuführen.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
#[Attribute(Attribute::TARGET_METHOD)] class Label {}Ein Attribut hängt Metadaten an eine Deklaration, ohne dort den Konstruktor auszuführen. Reflection liefert Deskriptoren und Argumente. Erst newInstance() erzeugt die Instanz und prüft das Ziel. Nach Attributklasse filtern, um fremde Metadaten auszulassen.
#[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"]
Beispiele
<?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]);
Ergebnis
[["daily"],"daily"]