PHP 8.3.4 Released!

ReflectionParameter::getAttributes

(PHP 8)

ReflectionParameter::getAttributesアトリビュートを取得する

説明

public ReflectionParameter::getAttributes(?string $name = null, int $flags = 0): array

この引数上で宣言されている全てのアトリビュートを、 ReflectionAttribute の配列として返します。

パラメータ

name

指定したクラス名にマッチするアトリビュートの、 ReflectionAttribute のみを含むようにフィルタします。

flags

name が指定されていた場合に、 結果をどうフィルタするかを決めるフラグ。

デフォルトは 0 です。 この場合、アトリビュートのクラス名が name であるものだけを返します。

他の利用可能なオプションは、 ReflectionAttribute::IS_INSTANCEOF です。 この場合、フィルタリングに instanceof を使います。

戻り値

アトリビュートの配列を、 ReflectionAttribute オブジェクトの配列として返します。

例1 基本的な使い方

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

Array
(
    [0] => Fruit
    [1] => Red
)

例2 クラス名で結果をフィルタする

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

Array
(
    [0] => Fruit
)

例3 クラス名、かつ継承も考慮して結果をフィルタする

<?php
interface Color {
}

#[
Attribute]
class
Fruit {
}

function
fruitBasket(
#[
Fruit]
#[
Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

Array
(
    [0] => Red
)

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top