Attribute inheritance | php-attribute-reader | Spatie

 SPATIE

php-attribute-reader
====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Php-attribute-reader](https://spatie.be/docs/php-attribute-reader/v1)  Usage  Attribute inheritance

 Version   v1

 Other versions for crawler [v1](https://spatie.be/docs/php-attribute-reader/v1)

- [ Introduction ](https://spatie.be/docs/php-attribute-reader/v1/introduction)
- [ Support us ](https://spatie.be/docs/php-attribute-reader/v1/support-us)
- [ Requirements ](https://spatie.be/docs/php-attribute-reader/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/php-attribute-reader/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/php-attribute-reader/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/php-attribute-reader/v1/changelog)
- [ About us ](https://spatie.be/docs/php-attribute-reader/v1/about-us)

Usage
-----

- [ Reading class attributes ](https://spatie.be/docs/php-attribute-reader/v1/usage/reading-class-attributes)
- [ Reading from specific targets ](https://spatie.be/docs/php-attribute-reader/v1/usage/reading-from-specific-targets)
- [ Discovering attributes ](https://spatie.be/docs/php-attribute-reader/v1/usage/discovering-attributes)
- [ Attribute inheritance ](https://spatie.be/docs/php-attribute-reader/v1/usage/attribute-inheritance)

 Attribute inheritance
=====================

###  On this page

1. [ Example ](#content-example)

All methods in this package use `ReflectionAttribute::IS_INSTANCEOF` by default. This means child attributes match when you query for a parent.

Example
-----------------------------------------------------------------------------

```
#[Attribute(Attribute::TARGET_CLASS)]
class CacheStrategy
{
    public function __construct(public int $ttl = 3600) {}
}

#[Attribute(Attribute::TARGET_CLASS)]
class AggressiveCache extends CacheStrategy
{
    public function __construct()
    {
        parent::__construct(ttl: 86400);
    }
}

#[AggressiveCache]
class ProductCatalog {}
```

Querying for the parent `CacheStrategy` will find the child `AggressiveCache`:

```
use Spatie\Attributes\Attributes;

$cache = Attributes::get(ProductCatalog::class, CacheStrategy::class);

$cache instanceof AggressiveCache; // true
$cache->ttl; // 86400
```

Querying for the exact child class works too:

```
$cache = Attributes::get(ProductCatalog::class, AggressiveCache::class);

$cache->ttl; // 86400
```

This applies to all methods: `get()`, `has()`, `getAll()`, `onMethod()`, `onProperty()`, `onConstant()`, `onParameter()`, `getAllOnMethod()`, `getAllOnProperty()`, `getAllOnConstant()`, `getAllOnParameter()`, `onFunction()`, and `find()`.
