Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Attribute Without Class

<?php

#[Attribute]
class y {
    function foo() { return __METHOD__; }
}

#[X, Y]
function f() { }

$ref = new \ReflectionFunction('\f');

try {
    if ($ref->getAttributes()[0]->getName() === 'X') {
        print 'Look mom! No hands' . PHP_EOL;
    }

    if ($ref->getAttributes()[1]->getName() === 'Y') {
        print $ref->getAttributes()[1]->newInstance()->foo();
    }
} catch (\Error $e) {
    # other errors
    var_dump($e->getMessage());
}

?>

PHP 8.0 has an attribute feature, where extra options may be attached to various structures. The option is defined as a class, and is accessible via the Reflection API, and the getAttribute() method.

The attribute class is not necessary, per se. As long at the attribute is not instantiated, it is possible to rely only on the name of the attribute to handle specific behaviors.

See Also

PHP Features

Last updated: 10 September 2026