Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 147 ยท Advanced PHP

Attributes

Learn PHP 8 attributes - the #[...] syntax, built-ins like Override, Deprecated, NoDiscard and SensitiveParameter, and custom attributes read with Reflection.

Attributes (added in PHP 8.0) are structured labels you attach to classes, methods, functions, properties, parameters and constants. They're written as #[Name(arguments)] directly above or before the thing they describe. An attribute does nothing by itself: it's data about your code, sometimes called metadata. Either PHP itself reacts to it (the built-in attributes), or your own code reads it at run time through Reflection and acts on it.

Before PHP 8, frameworks put this kind of information in DocBlock comments like @Route("/users") and parsed the comment text, which was slow, fragile and invisible to PHP. Attributes are real syntax: PHP checks that they're well formed, their arguments are ordinary PHP expressions, and their names are classes that your editor and static analysers understand. Today you'll see them everywhere: routes in Symfony, validation rules, ORM column mappings, test markers in PHPUnit and Pest, and PHP's own #[\Override] and #[\Deprecated].

The syntax

An attribute starts with #[ and ends with ]. Inside goes a class name, optionally with arguments in parentheses, exactly like calling a constructor. Named arguments work too:

PHP
<?php
#[Route('/users', methods: ['GET'])]
final class UserController
{
    #[Inject]
    private Logger $logger;

    #[Route('/users/{id}')]
    public function show(#[FromPath] int $id): Response { /* ... */ }
}

A few rules:

  • You can put several attributes in one block, separated by commas (#[Inject, Lazy]), or use several blocks in a row.
  • Arguments must be constant expressions: literals, constants, arrays of them, enum cases, and (since PHP 8.1) new expressions. You can't call a function or use a variable.
  • Names follow normal namespace rules. Built-in attributes live in the global namespace, so inside a namespaced file write #[\Override] with a leading backslash, or import it with use Override;.
  • Because # starts a comment in older PHP versions, #[Foo] on its own line is simply ignored by PHP 7. That made it safe to adopt attributes gradually.

Built-in attributes PHP understands

PHP ships a small set of attributes that change how the engine behaves or what it reports. These are the ones you'll actually use.

#[\Override] (PHP 8.3)

Marks a method that is meant to override a parent method or implement an interface method. If no such method exists, for example because you misspelled the name or the parent method was renamed, PHP refuses to compile the class:

PHP Override catches a renamed parent method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Uncomment the EmailNotifier class and run it again. Because of the typo sendMesage, PHP stops before running anything, with Fatal error: EmailNotifier::sendMesage() has #[\Override] attribute, but no matching parent method exists. Without the attribute, the typo would silently create a new method, and calls would keep going to the parent's version. Inheritance shows more overriding rules.

#[\Deprecated] (PHP 8.4)

Marks your own functions, methods and class constants (and, since PHP 8.5, global constants) as deprecated. Using them emits an E_USER_DEPRECATED message, just like PHP's own deprecated functions, with your message and version:

PHP Deprecating your own API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

This example shows Deprecated messages on purpose: one for the method call and one for the constant, each naming the line of the caller. The code still runs; deprecations are warnings for developers. In production they go to the log, and tools like PHPStan report them during development.

#[\NoDiscard] (PHP 8.5)

Marks a function whose return value must not be ignored, typically because it returns a new value instead of changing its input. Calling it as a bare statement triggers a warning. If you really mean to throw the result away, say so with a (void) cast (also new in PHP 8.5):

PHP NoDiscard warns about ignored results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The Warning in the output is the point of this example: the line $total->add(250); looks like it changes $total, but it doesn't, so the first echo still prints 500. That's exactly the class of bug #[\NoDiscard] exists to catch. Several built-in functions got the same treatment in PHP 8.5. Using Built-in Functions has more on it.

#[\SensitiveParameter] (PHP 8.2)

Stack traces include function arguments, and they end up in log files and error trackers. Mark a parameter as sensitive and PHP replaces its value in every trace with a SensitiveParameterValue object, so passwords and API keys never reach the log:

PHP Hiding secrets in stack traces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The trace shows 'app' for the user but Object(SensitiveParameterValue) for the password. Add it to every parameter that holds a password, token, key or card number, as recommended in Password Hashing.

Other built-ins

Attribute Since Purpose
#[\Attribute] 8.0 Declares that a class can be used as an attribute (see below)
#[\ReturnTypeWillChange] 8.1 Silences the deprecation when an old method overriding a built-in one lacks a return type
#[\AllowDynamicProperties] 8.2 Allows dynamic properties on a class (they're deprecated otherwise)
#[\SensitiveParameter] 8.2 Hides a parameter's value in stack traces
#[\Override] 8.3 Requires a matching parent or interface method
#[\Deprecated] 8.4 Emits deprecation messages for your own functions and constants
#[\NoDiscard] 8.5 Warns when a return value is ignored

Writing your own attributes

A custom attribute is an ordinary class marked with #[\Attribute]. The attribute's arguments become the constructor's arguments. By default an attribute can go on any target and only once per target; pass flags to restrict that:

PHP
<?php
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::IS_REPEATABLE)]
final class Length
{
    public function __construct(public int $min = 0, public int $max = PHP_INT_MAX) {}
}

The target flags are TARGET_CLASS, TARGET_FUNCTION, TARGET_METHOD, TARGET_PROPERTY, TARGET_CLASS_CONSTANT, TARGET_PARAMETER, TARGET_CONSTANT (PHP 8.5) and TARGET_ALL (the default). IS_REPEATABLE allows the same attribute several times on one target.

Reading attributes with Reflection

Code reads attributes through the Reflection API: every reflection object (ReflectionClass, ReflectionMethod, ReflectionProperty, ReflectionParameter, ...) has a getAttributes() method. It returns ReflectionAttribute objects, which give you the name and arguments, and newInstance() creates the attribute object itself:

PHP Reading a custom attribute

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Two details worth knowing. First, PHP doesn't create the attribute object or even check that the attribute class exists until you call newInstance(). You can read the name and arguments of any attribute, even one whose class isn't loaded. Second, target and repeat rules are also validated at newInstance() time, which throws an Error if, say, a class-only attribute was placed on a method.

Passing a class name to getAttributes() filters the list. Add the flag ReflectionAttribute::IS_INSTANCEOF to also match subclasses or interface implementations, which is handy when several attributes share a common interface.

Example: a mini validator

Here's the pattern frameworks use for validation: describe the rules next to the properties, then let one generic function enforce them for any class. All rule attributes implement a small interface, so the validator doesn't need to know them individually:

PHP Validation rules as attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice where the attributes sit: on promoted constructor parameters. PHP applies them to both the parameter and the property it creates, which is why getProperties() finds them. Adding a rule now means writing one class and one attribute line; validate() never changes. Compare this with the hand-written checks in Form Validation.

Example: routes from attributes

Routing is the other classic. A controller declares its URLs right above its methods, and a small router collects them with Reflection:

PHP A router that reads Route attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The URL placeholders become named regex groups, and the matched values are passed to the method as named arguments by spreading the string-keyed array. Real frameworks cache the collected routes so Reflection runs once per deploy, not once per request. Front Controllers and Routing builds the same router with closures instead.

Keep attributes declarative. They should describe what (this property is required, this method answers GET /articles), while ordinary code decides how. If you find yourself putting logic into attribute arguments, a plain method call is probably clearer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens at run time when PHP reaches a class with a custom attribute like #[Table('users')]?

    Custom attributes are stored as metadata. The attribute class is only loaded and constructed when code calls newInstance() on a ReflectionAttribute.
  2. 2. A child class marks a method with #[\Override], but the parent has no method of that name. What happens?

    #[\Override] (PHP 8.3) makes PHP verify the override at compile time. A missing parent or interface method is a fatal error.
  3. 3. Which of these is NOT allowed as an attribute argument?

    Attribute arguments must be constant expressions. Literals, constants, enum cases, arrays of them and new expressions work; function calls and variables do not.
  4. 4. What does #[\SensitiveParameter] change?

    It only affects backtraces, so secrets don't end up in logs and error reports. The function still receives the real value.
  5. 5. How do you call a #[\NoDiscard] function and deliberately ignore its result without a warning in PHP 8.5?

    PHP 8.5 added the (void) cast for exactly this purpose. It documents that throwing the value away is intentional.

Summary

  • Attributes (PHP 8.0) are metadata written as #[Name(args)] on classes, functions, methods, properties, parameters and constants. Arguments are constant expressions; named arguments work.
  • Built-ins change engine behavior: #[\Override] (8.3) verifies overrides, #[\Deprecated] (8.4) emits deprecations for your API, #[\NoDiscard] (8.5) warns about ignored results (silence with (void)), #[\SensitiveParameter] (8.2) hides secrets in traces.
  • A custom attribute is a class marked #[\Attribute], optionally restricted with TARGET_* flags and made repeatable with IS_REPEATABLE.
  • Read attributes with getAttributes() on any Reflection object; newInstance() builds the attribute object and validates targets. Filter by class, or by interface with ReflectionAttribute::IS_INSTANCEOF.
  • Attributes on promoted constructor parameters apply to the property too.
  • Validation rules, routes, ORM mappings and test markers are classic uses. Keep attributes declarative and cache what you collect from them.

Next: Reflection