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

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

「 获取指定类常量的属性 」


函数名称:ReflectionClassConstant::getAttributes()

适用版本:PHP 8.0.0 及以上

函数说明:该函数用于获取指定类常量的属性。

用法示例:

class MyClass {
    #[Attribute1]
    const CONSTANT_ONE = 'value1';
    
    #[Attribute2('param')]
    const CONSTANT_TWO = 'value2';
}

$reflection = new ReflectionClassConstant('MyClass', 'CONSTANT_ONE');
$attributes = $reflection->getAttributes();

foreach ($attributes as $attribute) {
    $attributeName = $attribute->getName(); // 获取属性名称
    $attributeArgs = $attribute->getArguments(); // 获取属性参数

    echo "Attribute: $attributeName\n";
    echo "Arguments:\n";
    foreach ($attributeArgs as $arg) {
        echo "- $arg\n";
    }
}

输出结果:

Attribute: Attribute1
Arguments:

Attribute: Attribute2
Arguments:
- param

在上述示例中,我们定义了一个名为MyClass的类,其中有两个常量CONSTANT_ONECONSTANT_TWO。每个常量都带有不同的属性。

我们通过创建ReflectionClassConstant对象并传入类名和常量名来获取常量的反射。然后,我们使用getAttributes()方法获取常量的属性。

在循环中,我们可以使用getName()方法获取属性的名称,并使用getArguments()方法获取属性的参数。在本例中,Attribute1没有参数,而Attribute2有一个参数param

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

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