bhylu.com

Advertisements

PHP Attributes and Reflection

Attributes attach structured metadata to declarations. Reflection can inspect it, but the metadata does nothing until code interprets it.

How it works

Declare an attribute class with the targets it supports, then use reflection to read instances. This mechanism can support routing, validation or mapping libraries, but it does not make arbitrary metadata safe to execute. Keep the boundary between declared data and the consumer explicit. Do not instantiate classes selected directly from an untrusted request merely because reflection can discover them.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l attributes-reflection.php
php attributes-reflection.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · attributes-reflection.php

<?php
declare(strict_types=1);

#[Attribute(Attribute::TARGET_CLASS)]
class Reviewed { public function __construct(public string $area) {} }
#[Reviewed("lending")]
class LoanSummary {}
$type = new ReflectionClass(LoanSummary::class);
$attribute = $type->getAttributes(Reviewed::class)[0]->newInstance();
echo $attribute->area, "\n";

Expected result

lending

The declaration stores a lending label and reflection retrieves the explicitly selected attribute. The attribute does not validate LoanSummary or publish a review result automatically. A real framework consumer would need its own policy for supported attributes and failure handling.

Check the official PHP manual for detailed version and API contracts.