函数名:ReflectionProperty::getModifiers()
适用版本:所有 PHP 版本
用法:该方法用于获取属性的修饰符。修饰符表示属性的访问级别和其他特性。
语法:int ReflectionProperty::getModifiers( void )
参数:无
返回值:返回一个整数,表示属性的修饰符。可以使用 ReflectionProperty::IS_* 常量进行解析。
示例:
class MyClass {
public $publicProperty;
protected $protectedProperty;
private $privateProperty;
}
$reflector = new ReflectionClass('MyClass');
$properties = $reflector->getProperties();
foreach ($properties as $property) {
$modifiers = $property->getModifiers();
if ($modifiers & ReflectionProperty::IS_PUBLIC) {
echo $property->getName() . ' is public.' . PHP_EOL;
}
if ($modifiers & ReflectionProperty::IS_PROTECTED) {
echo $property->getName() . ' is protected.' . PHP_EOL;
}
if ($modifiers & ReflectionProperty::IS_PRIVATE) {
echo $property->getName() . ' is private.' . PHP_EOL;
}
}
输出结果:
publicProperty is public.
protectedProperty is protected.
privateProperty is private.
该示例中,我们定义了一个名为 MyClass 的类,并在其中定义了三个属性:publicProperty、protectedProperty 和 privateProperty。通过使用 ReflectionProperty 类,我们可以获取属性的修饰符并判断其访问级别。在循环中,我们使用 ReflectionProperty::getModifiers() 方法获取修饰符,并通过按位与运算符和 ReflectionProperty::IS_* 常量进行解析。最后,我们根据修饰符的不同输出相应的信息。在本示例中,我们输出了每个属性的访问级别。