English | 简体中文 | 繁體中文
查询

ReflectionClass::getAttributes()函数—用法及示例

「 获取类的属性 」


ReflectionClass::getAttributes()函数用于获取类的属性。

用法:

ReflectionAttribute[] ReflectionClass::getAttributes( string $name = NULL, int $flags = 0 )

参数:

  • $name(可选):要筛选的属性名称。
  • $flags(可选):要应用的过滤器标志。

返回值:

  • 返回一个ReflectionAttribute对象的数组,或者在失败时返回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";
}

在上面的示例中,我们定义了一个名为MyClass的类,并在其中的$myProperty属性上使用了#[MyAttribute]属性。然后,我们使用ReflectionClass创建了一个反射类的实例,并使用getAttributes()方法获取了类的属性。

然后,我们使用foreach循环遍历属性数组,并使用getName()方法获取属性的名称,使用getArguments()方法获取属性的参数,使用getTarget()方法获取属性的目标(在这里是属性)。

最后,我们将属性的名称、参数和目标打印出来。

补充纠错
热门PHP函数
分享链接