phpday 2027 - Call for Papers

ReflectionAttribute::getTarget

(PHP 8)

ReflectionAttribute::getTarget — アトリビュートが適用されているターゲットを返す

説明

public function ReflectionAttribute::getTarget(): int

このアトリビュートが実際に適用されているターゲット(クラス、プロパティなど)を返します。 これは、アトリビュートクラスで許可されているターゲットとは異なります。

パラメータ

この関数にはパラメータはありません。

戻り値

アトリビュートが適用されているターゲットを表す Attribute::TARGET_* 定数 を返します。 一方、アトリビュートクラスで許可されているターゲットは、 そのクラスに適用されている Attribute のインスタンスの flags プロパティから取得できます。

例

例1 アトリビュートの実際のターゲットと許可されているターゲットを区別する

<?php
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class Marker {}

#[Marker]
class Example
{
    #[Marker]
    public $value;
}

$class = new ReflectionClass(Example::class);
$property = new ReflectionProperty(Example::class, 'value');

var_dump($class->getAttributes(Marker::class)[0]->getTarget());
var_dump($property->getAttributes(Marker::class)[0]->getTarget());

$definition = new ReflectionClass(Marker::class);
var_dump($definition->getAttributes(Attribute::class)[0]->newInstance()->flags);
?>

上の例の出力は以下となります。

int(1)
int(8)
int(9)

User Contributed Notes

There are no user contributed notes for this page.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top