【发布时间】:2021-02-03 22:30:05
【问题描述】:
我有一个 PHP 属性如下:
#[Attribute(Attribute::TARGET_PROPERTY|Attribute::TARGET_METHOD|Attribute::TARGET_PARAMETER)]
class NotNull implements Constraint{
...
}
现在,我想获取属性反射的所有属性的列表并检查它们是否是约束的实例:
$propertyReflection = ...;
$attributes = $propertyReflection->getAttributes();
foreach($attributes as $attribute){
if($attribute instanceof Constraint){
// do something
}
}
但是,它什么都不做?
那么,我的问题是:是否可以用一个属性实现一个接口,然后检查该属性是否是一个实例?
这是完整的代码:
$reflection = new ReflectionClass($type);
$properties = $reflection->getProperties();
foreach ($properties as $property) {
$attributes = $property->getAttributes();
foreach ($attributes as $attribute) {
if (attribute instanceof Constraint)) {
// do something
}
}
}
【问题讨论】:
-
$propertyReflection = ...;这行实际上说了什么?我假设您使用的是反射器而不是实际的对象?
标签: php reflection php-8