In this chapter
We'll learn attributes — structured labels on classes, methods, properties and parameters that PHP and your own code can read — the built-in ones (Override, Deprecated, SensitiveParameter, AllowDynamicProperties, NoDiscard), how to write and read a custom attribute with reflection, how they compare with Java annotations, C# attributes and Python decorators (which PHP doesn't have), and a checklist for modern OOP design.
The Problem in Real Life
Two last requests before the classes are done. Olivia wants every booking note limited to 200 characters, checked in one place. And oldPrice() — replaced weeks ago by calculatePrice() — is still called in three places, although its doc comment says @deprecated.
"A comment is for people," says Marcus. "PHP never reads it, so nobody's told. We need labels that code can read." He writes #[\Deprecated] above oldPrice(), and the next run of the site logs all three callers.
The doc comment said deprecated for weeks. Why did nobody notice?
Mia
Comments for People vs. Labels for Code
Comments are invisible to PHP
@deprecated in a doc comment is only text. PHP runs past it without a word.
Labels with meaning
An attribute is structured data attached to code — PHP, frameworks and your own code can read it.
Describe, don't do
An attribute changes nothing by itself. Something has to read it — unlike Python's decorators.
Attributes and Modern OOP Design
Metadata in the code: attributes, added in PHP 8.0, attach structured information to classes, methods, functions, properties, constants and parameters. This chapter covers:
- Attribute syntax:
#[Name(arguments)]. - Built-in attributes: the ones PHP itself acts on.
- Custom attributes: writing your own and reading them with reflection.
- Other languages: Java annotations, C# attributes, Python decorators.
- Modern OOP design: everything from Acts 11 and 12, as a checklist.
Attribute syntax: an attribute is written #[Name] or #[Name(arguments)] on the line before what it describes, and several can be combined: #[A, B(1)]. The name is a class name — a built-in one like \Deprecated (the backslash means "PHP's own", Act 13) or one of yours — and the arguments follow the rules of a constructor call, including named arguments. That's why a comment written as #[like this] is a parse error (Act 02). On its own, an attribute does nothing: it's information. It only matters when something reads it — PHP itself for the built-in ones, or a framework or your own code for custom ones.
Built-in attributes: PHP reads a handful of its own. #[\Override] (PHP 8.3) checks that a method really overrides something (Act 11). #[\Deprecated] (PHP 8.4) makes PHP emit a deprecation notice, with your message, every time the function or method is called — the fix for oldPrice(). #[\SensitiveParameter] (PHP 8.2) hides a parameter's value from stack traces, so passwords and card numbers don't end up in logs. #[\AllowDynamicProperties] (PHP 8.2, chapter 7) permits dynamic properties on a class. #[\ReturnTypeWillChange] silences a deprecation when old code overrides a built-in method without a return type. And #[\NoDiscard] (PHP 8.5) warns when a function's return value is ignored — useful for methods like Money::plus() that return a new object instead of changing the old one (Act 11).
<?php/** @deprecated use calculatePrice() */ // a comment: PHP ignores itfunction oldPriceComment(): int{return 2500;}#[\Deprecated("use calculatePrice() instead", since: "2026-11")]function oldPrice(): int{return 2500;}oldPriceComment(); // silenceoldPrice();// Deprecated: Function oldPrice() is deprecated since 2026-11, use calculatePrice() instead
<?phpdeclare(strict_types=1);function chargeCard(string $customer, #[\SensitiveParameter] string $cardNumber): void{throw new RuntimeException("Payment failed");}try {chargeCard("Clare Lefèvre", "4111111111111111");} catch (RuntimeException $e) {echo str_contains($e->getTraceAsString(), "4111") ? "card number in the trace!" : "card number hidden", "\n";}// card number hiddenfinal readonly class Money{public function __construct(public int $pence) {}#[\NoDiscard("plus() returns a new Money; the original doesn't change")]public function plus(int $pence): Money{return new Money($this->pence + $pence);}}$price = new Money(2500);$price->plus(250); // result ignored: a classic immutability mistakeecho $price->pence, "\n";// Warning: The return value of method Money::plus() should either be used or intentionally ignored by casting it as (void), plus() returns a new Money; the original doesn't change// 2500
Custom attributes: any class marked with #[\Attribute] can be used as an attribute, and the flags say where: #[\Attribute(\Attribute::TARGET_PROPERTY)]. Then #[MaxLength(200)] above a property stores that information. To use it, code asks PHP's reflection API — classes like ReflectionProperty that describe code from inside — for the attributes: getAttributes(MaxLength::class) returns them, and ->newInstance() builds the attribute object with its arguments. A small validator can loop over a class's properties, read every MaxLength, and check the values. This is how frameworks work: Symfony and Laravel read attributes for routes, validation rules, database mapping and event listeners, so a class describes itself in one place. The diagram below shows how a custom attribute turns into a check.
From #[MaxLength(20)] to a validation error
#[MaxLength(20)] public string $note
only a label: PHP stores it, does nothing
new ReflectionObject($booking)
your validator inspects the class
->getAttributes(MaxLength::class)
finds the label and its arguments
->newInstance()
builds new MaxLength(20)
mb_strlen($note) > 20?
→ "note is longer than 20 characters"
<?phpdeclare(strict_types=1);#[\Attribute(\Attribute::TARGET_PROPERTY)]final readonly class MaxLength{public function __construct(public int $max) {}}final class BookingNote{public function __construct(#[MaxLength(20)] public string $note,#[MaxLength(40)] public string $customer,) {}}function validate(object $object): array{$errors = [];foreach ((new ReflectionObject($object))->getProperties() as $property) {foreach ($property->getAttributes(MaxLength::class) as $attribute) {$rule = $attribute->newInstance(); // builds MaxLength(20)$value = $property->getValue($object);if (mb_strlen($value) > $rule->max) {$errors[] = "{$property->getName()} is longer than {$rule->max} characters";}}}return $errors;}print_r(validate(new BookingNote("Likes a short fade and a hot towel", "Clare Lefèvre")));// Array// (// [0] => note is longer than 20 characters// )
Annotations, attributes and decorators: Java has annotations (@Override, @Deprecated, custom ones read by reflection) and C# has attributes ([Obsolete]) — PHP's attributes are the same idea, and before PHP 8 frameworks imitated them with @ tags in doc comments, which you'll still see in older code. Python's decorators look similar (@cache above a function) but are fundamentally different: a decorator is a function that wraps or replaces the decorated function when it's defined, changing what it does. PHP doesn't have decorators: an attribute never changes behaviour by itself. To wrap behaviour around a function in PHP, you wrap it explicitly — a higher-order function or a closure (Act 09), or middleware in a framework.
# Python — a decorator WRAPS the function when it's definedimport functoolsdef logged(func):@functools.wraps(func)def wrapper(*args):print(f"calling {func.__name__}{args}")return func(*args)return wrapper@logged # price is now the wrapperdef price(pence):return pence * 2price(2500) # prints: calling price(2500,)# PHP: #[Logged] would only be a label. To wrap behaviour, wrap explicitly:# $price = logged(fn(int $p) => $p * 2); (a higher-order function, Act 09)
// Java — @Deprecated and @Override are read by the compiler; custom ones by reflection@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)@interface MaxLength { int value(); }class BookingNote {@MaxLength(20) String note;@Deprecatedint oldPrice() { return 2500; }@Overridepublic String toString() { return note; }}
readonly, const, final or enum — which one?: four modern tools all mean some version of "this doesn't change", and they're easy to confuse. A class constant is one fixed value for the whole class (Booking::MAX_PER_DAY). A readonly property is set once per object and then fixed (each booking's price). final isn't about values at all: it stops a class from being extended or a method or constant from being overridden. And an enum is a fixed set of possible values — a type. The table below compares them; choosing the right one makes the code say exactly what it means.
| Tool | Fixes what? | Per object or per class? | Example |
|---|---|---|---|
| const | One value | Per class | const MAX_PER_DAY = 16; |
| readonly | A property's value after it's set once | Per object | public readonly Money $price; |
| readonly class | Every property's value | Per object | readonly class Money { … } |
| final | The design: no extending or overriding | Class, method or constant | final class Money |
| enum | The set of possible values (a type) | Per type | enum BookingStatus { case Pending; … } |
Modern OOP design, in one list: Acts 11 and 12 add up to a short checklist. Fixed sets of values are enums. Small values are final readonly value objects. Data that may only change through rules uses private(set) and methods; data with a rule on every write uses a hook. Classes are final unless designed for extension, depend on interfaces, and receive dependencies through the constructor. Magic methods stay strict and rare. Attributes carry metadata, types are everywhere, and PHPStan (Act 21) checks what PHP can't. The table below lists the attributes you'll meet.
| Attribute | Since | What happens |
|---|---|---|
| #[\Override] | PHP 8.3 | Error if the method doesn't override anything |
| #[\Deprecated] | PHP 8.4 | A deprecation notice on every call |
| #[\SensitiveParameter] | PHP 8.2 | The value is hidden in stack traces |
| #[\AllowDynamicProperties] | PHP 8.2 | Dynamic properties allowed on the class |
| #[\ReturnTypeWillChange] | PHP 8.1 | Silences a missing-return-type deprecation |
| #[\NoDiscard] | PHP 8.5 | A warning when the return value is ignored |
| #[\Attribute] | PHP 8.0 | Marks a class as a custom attribute |
| Your own, e.g. #[MaxLength(200)] | — | Nothing, until your code reads it with reflection |
Key Takeaway
Attributes (#[Name(args)], PHP 8.0) attach structured metadata to code; they do nothing until something reads them. PHP acts on its built-ins: Override, Deprecated (8.4), SensitiveParameter, AllowDynamicProperties, ReturnTypeWillChange and NoDiscard (8.5). Custom attributes are classes marked #[\Attribute], read with reflection (getAttributes()->newInstance()) — how frameworks map routes, validation and databases. They match Java annotations and C# attributes; Python decorators, which wrap and change functions, have no PHP equivalent.
Why This Matters
Attributes let a class describe itself where it's written — "this property has at most 200 characters", "this method is deprecated", "this parameter is a secret" — and let PHP, frameworks and your tools act on it. Comments can't do that.
You'll see attributes on almost every class in modern frameworks: routes, validation, serialization and database mapping in Symfony, and more and more in Laravel. And knowing that they're labels, not decorators, tells you where to look for the code that actually does the work.
oldPrice() reports its last three callers, notes are validated by one #[MaxLength(200)], and the log is quiet. BookBay's classes now use everything modern PHP offers. One job is left for this Act: refactor the booking classes from the start of the week — string status, getters and setters, a dynamic note and an inherited factory — into modern PHP. That's the checkpoint.
