welcomattic / has-attributes
检查一个类、方法或属性是否具有属性
v1.1.0
2023-11-27 13:25 UTC
Requires
- php: >=8.2
Requires (Dev)
- phpunit/phpunit: ^10.4
README
多年来,PHP 使得检查一个对象是否为给定类的实例变得简单。然而,检查对象的类是否具有属性却并不那么简单。
本包提供了一些函数,使检查对象的类是否具有指定的属性变得更加容易。
安装
$ composer require welcomattic/has-attribute
用法
use Welcomattic\HasAttribute\HasAttributeMode; #[\Attribute(\Attribute::TARGET_CLASS)] class ClassAttribute {} #[\Attribute(\Attribute::TARGET_CLASS)] class SecondClassAttribute {} #[\Attribute(\Attribute::TARGET_CLASS)] class ThirdClassAttribute {} #[ClassAttribute] #[SecondClassAttribute] class Foo {} class_has_attribute(Foo::class, ClassAttribute::class); // true class_has_attribute(Foo::class, ThirdClassAttribute::class); // false class_has_attribute(Foo::class, [ClassAttribute::class, SecondClassAttribute::class]); // true class_has_attribute(Foo::class, [ClassAttribute::class, SecondClassAttribute::class], HasAttributeMode::ATTRIBUTES_ALL_OF); // true (default mode) class_has_attribute(Foo::class, [ClassAttribute::class, SecondClassAttribute::class], HasAttributeMode::ATTRIBUTES_ANY_OF); // true class_has_attribute(Foo::class, [ClassAttribute::class, SecondClassAttribute::class], HasAttributeMode::ATTRIBUTES_ONE_OF); // false
您也可以检查对象的方法或属性
#[\Attribute(\Attribute::TARGET_METHOD)] class MethodAttribute {} #[\Attribute(\Attribute::TARGET_PROPERTY)] class PropertyAttribute {} class Foo { #[MethodAttribute] public function bar() {} #[PropertyAttribute] public $baz; } method_has_attribute(Foo::class, MethodAttribute::class, 'bar'); // true property_has_attribute(Foo::class, PropertyAttribute::class, 'baz'); // true
它还支持属性继承
#[\Attribute(\Attribute::TARGET_CLASS)] class ClassAttributeInterface {} #[\Attribute(\Attribute::TARGET_CLASS)] class ChildClassAttribute extends ClassAttributeInterface {} #[ChildClassAttribute] class Foo {} class_has_attribute(Baz::class, [ClassAttributeInterface::class]); // true
致谢
本包基于 lyrixx 的想法,并由 welcomattic 和 Korbeil 实现。