Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / PHP

Atributi in refleksija

Atribut deklaraciji doda metapodatke brez klica konstruktorja na mestu uporabe.

Različica: PHP 8.4; repository runtime, production runtime not attested

Sintaksa

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

Atribut deklaraciji doda metapodatke brez klica konstruktorja na mestu uporabe. Refleksija prebere opisnike in argumente. newInstance() ustvari primerek in preveri cilj. Filtriranje po razredu izloči nepovezane metapodatke.

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

Primeri

<?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]);

Rezultat

[["daily"],"daily"]

Viri