php - 是否可以使用 PHP 8 属性实现接口并检查它是否是该接口的实例?
问题描述
我有一个 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
}
}
}
解决方案
这不起作用,因为它还不是您$attribute
的类ReflectionAttribute
的实例。NotNull
要解决此问题,您需要对其进行实例化,然后检查它是否是正确的实例。
if($attribute->newInstance() instanceof Constraint)
// do something
您可以在3v4l.org上看到它正在运行。
如果您出于任何特定原因不想实例化它,因为它会做您认为不必要的事情,您还可以使用更多反射技术检查属性是您期望的类。
(new ReflectionClass($attribute->getName()))
->implementsInterface(Constraint::class)
推荐阅读
- c# - 是否有关于运行 INSERT 的频率上限的最佳实践?
- maven - Gradle - 无法使用 thingsboard 中指定的 Gradle 分布创建工具 API 实现的实例
- rust - 逗号分隔的 syn::Idents 列表
- c - 为什么不能为 *P 分配数字?
- ios - 在 iOS 版 Google Analytics(分析)中跟踪自然搜索流量
- xquery - and-query 匹配一个属性值和一个子元素值
- oauth-2.0 - 使用 symfony 4 获取 OAuth 凭据时出错:“invalid_client”
- kotlin - 当使用可变列表编译器的 .remove 函数抛出异常时,还有什么选择吗?
- powershell - 使用powershell手动创建文件索引,制表符分隔
- flutter - 未知操作系统