リフレクションAPI を使ってアトリビュートを読み取る

クラス、メソッド、関数、パラメータ、プロパティ、クラス定数からアトリビュートにアクセスするために、 リフレクションAPI は対応するリフレクションオブジェクトに getAttributes() メソッドを提供しています。 このメソッドを使うと、 アトリビュートの名前や引数で問い合わせを行うことができ、 アトリビュートを表現するクラスをインスタンス化させることができます。 このメソッドは、ReflectionAttribute のインスタンスの配列を返します。

リフレクションされたアトリビュートの表現と、 実際のインスタンスを分離することで、 アトリビュートのクラスが存在しなかったり、 タイピングミスや引数の不足に関するエラーをプログラマが制御しやすくなります。 ReflectionAttribute::newInstance() を呼び出した後のみ、 アトリビュートクラスのオブジェクトはインスタンス化でき、 引数が合っているかを検証できます。これ以前のタイミングでは出来ません。

例1 リフレクションAPIを使い、アトリビュートを読み取る

<?php

#[Attribute]
class
MyAttribute
{
public
$value;

public function
__construct($value)
{
$this->value = $value;
}
}

#[
MyAttribute(value: 1234)]
class
Thing
{
}

function
dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();

foreach (
$attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpAttributeData(new ReflectionClass(Thing::class));
/*
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
*/

アトリビュートクラスの名前を渡すことで、 リフレクションインスタンスの全てのアトリビュートをループさせる代わりに、 特定のアトリビュートのクラスだけを取得することができます。

例2 リフレクションAPIを使い、特定のアトリビュートを読み取る

<?php

function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);

foreach (
$attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpMyAttributeData(new ReflectionClass(Thing::class));
add a note

User Contributed Notes 1 note

up
6
Hirusha Sharma
3 years ago
Fetch properties from functions:

----------------------------------------
Function definition with attributes:
----------------------------------------
#[ReadOnly]
#[Property(type: 'function', name: 'Hello')]
function Hello()
{
return "Hello";
}

-----------------------------------------
Gather attributes from the function
-----------------------------------------
function getAttributes(Reflector $reflection)
{
$attributes = $reflection->getAttributes();
$result = [];
foreach ($attributes as $attribute)
{
$result[$attribute->getName()] = $attribute->getArguments();
}
return $result;
}

$reflection = new ReflectionFunction("Hello");
print_r(getAttributes($reflection));

-----------------------------
OUTPUT
-----------------------------
Array
(
[ReadOnly] => Array
(
)

[Property] => Array
(
[type] => function
[name] => Hello
)

)
To Top