Znalostní bázeCentrum zkoušek
CSČeština
Vybrat jazyk13

CKTIS / PHP

Atributy a reflexe

Atribut připojí metadata k deklaraci bez volání konstruktoru v místě použití.

Verze: PHP 8.4; repository runtime, production runtime not attested

Syntaxe

#[Attribute(Attribute::TARGET_METHOD)] class Label {}

Atribut připojí metadata k deklaraci bez volání konstruktoru v místě použití. Reflexe načte popisovače a argumenty. Až newInstance() vytvoří instanci a ověří cíl. Výběr třídy atributu zabrání vytváření nesouvisejících metadat.

#[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"]

Pří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ýsledek

[["daily"],"daily"]

Zdroje