PHP code example of welcomattic / has-attributes

1. Go to this page and download the library: Download welcomattic/has-attributes library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

welcomattic / has-attributes example snippets


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