PHP code example of brenoroosevelt / php-attributes

1. Go to this page and download the library: Download brenoroosevelt/php-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/ */

    

brenoroosevelt / php-attributes example snippets




$myAttribute = Attr::class;
$attributes = [];
$relfectionClass = new ReflectionClass(MyClass::class);
foreach ($relfectionClass->getAttributes($myAttribute) as $attribute) {
    $attributes[] = $attribute;
}

foreach ($relfectionClass->getMethods() as $methods) {
    foreach ($methods->getAttributes($myAttribute) as $attribute) {
        $attributes[] = $attribute;
    }
}

foreach ($relfectionClass->getProperties() as $property) {
     /** ... */
}

foreach ($relfectionClass->getReflectionConstants() as $property) {
    /** ... */
}

$instances = array_map(fn(ReflectionAttribute $attr) => $attr->newInstance(), $attributes);


use BrenoRoosevelt\PhpAttributes\Attributes;

$instances = Attributes::extract(MyAttr::class)->fromClass(MyClass::class)->getInstances();


use BrenoRoosevelt\PhpAttributes\ParsedAttribtubeCollection;

$extract = 
     Attributes::extract(
        // $attribute: the attribute name (string)
        // default values is NULL (search for all attributes)
        Attribute::class,
        
        // $flag: flags to filter attributes.     
        // default values is 0 (no filter will be applied)
        ReflectionAttribute::IS_INSTANCEOF
    );


/* $attributes = Attributes::extract()->from... */ 

// Collection
$attributes->add(new ParsedAttribute(...)) // new Collection instance (immutable)
$attributes->merge(new Collection);        // new Collection instance (immutable)
$attributes->getInstances();               // object[] array with attributes instances
$attributes->getTargets();                 // Reflector[] array with Reflection objects target by attributes
$attributes->getAttributes();              // ReflectionAttribute[]
$attributes->count();                      // int
$attributes->isEmpty();                    // bool
$attributes->first();                      // null|(object) ParsedAttribute
$attributes->toArray();                    // ParsedAttribute[]

// Iterable (ParsedAttribute[])
foreach ($attributes as $attr) {
    $attr->attribute(); // ReflectionAttribute
    $attr->target();    // ReflectionClass|ReflectionClassConstant|
                        // ReflectionProperty|ReflectionMethod|ReflectionParameter
}

bash
composer