ReflectionFunctionAbstract::getAttributes

アトリビュートを取得する

説明

public array ReflectionFunctionAbstract::getAttributes(stringnull $name = null, int $flags = 0)

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

パラメータ

name

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

flags

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

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

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

戻り値

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

例1 メソッドを使った、基本的な使い方

<?php
#[Attribute]
class 
Fruit {
}

#[
Attribute]
class 
Red {
}

class 
Factory {
    #[
Fruit]
    #[
Red]
    public function 
makeApple(): string
    
{
        return 
'apple';
    }
}

$method = new ReflectionMethod('Factory''makeApple');
$attributes $method->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

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

例2 関数を使った、基本的な使い方

<?php
#[Attribute]
class 
Fruit {
}

#[
Attribute]
class 
Red {
}

#[
Fruit]
#[
Red]
function 
makeApple(): string
{
    return 
'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes $function->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

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

例3 クラス名を使って結果をフィルタする

<?php
#[Attribute]
class 
Fruit {
}

#[
Attribute]
class 
Red {
}

#[
Fruit]
#[
Red]
function 
makeApple(): string
{
    return 
'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes $function->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

Array
(
    [0] => Fruit
)

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

<?php
interface Color {
}

#[
Attribute]
class 
Fruit {
}

#[
Attribute]
class 
Red implements Color {
}

#[
Fruit]
#[
Red]
function 
makeApple(): string
{
    return 
'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes $function->getAttributes('Color'ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

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

Array
(
    [0] => Red
)

参考

  • ReflectionClass::getAttributes
  • ReflectionClassConstant::getAttributes
  • ReflectionParameter::getAttributes
  • ReflectionProperty::getAttributes