ReflectionClass::getAttributes()
函數(shù)用于獲取類的屬性。
用法:
ReflectionAttribute[] ReflectionClass::getAttributes( string $name = NULL, int $flags = 0 )
參數(shù):
$name
(可選):要篩選的屬性名稱。$flags
(可選):要應(yīng)用的過濾器標(biāo)志。
返回值:
- 返回一個(gè)ReflectionAttribute對(duì)象的數(shù)組,或者在失敗時(shí)返回false。
示例:
class MyClass
{
#[MyAttribute]
public $myProperty;
}
$reflectionClass = new ReflectionClass('MyClass');
$attributes = $reflectionClass->getAttributes();
foreach ($attributes as $attribute) {
$attributeName = $attribute->getName();
$attributeArguments = $attribute->getArguments();
$attributeTarget = $attribute->getTarget();
echo "Attribute name: $attributeName\n";
echo "Attribute arguments: ";
print_r($attributeArguments);
echo "Attribute target: $attributeTarget\n";
}
在上面的示例中,我們定義了一個(gè)名為MyClass
的類,并在其中的$myProperty
屬性上使用了#[MyAttribute]
屬性。然后,我們使用ReflectionClass
創(chuàng)建了一個(gè)反射類的實(shí)例,并使用getAttributes()
方法獲取了類的屬性。
然后,我們使用foreach
循環(huán)遍歷屬性數(shù)組,并使用getName()
方法獲取屬性的名稱,使用getArguments()
方法獲取屬性的參數(shù),使用getTarget()
方法獲取屬性的目標(biāo)(在這里是屬性)。
最后,我們將屬性的名稱、參數(shù)和目標(biāo)打印出來。