Table of Contents
What Do Attributes Look Like?
How Are Attributes Different from PHPDoc?
How to Define and Use Custom Attributes
Step 1: Define the Attribute Class
Step 2: Apply the Attribute
Where Are Attributes Commonly Used?
A Few Things to Keep in Mind
Home Backend Development PHP Tutorial What are attributes (annotations) in PHP 8?

What are attributes (annotations) in PHP 8?

Jun 22, 2025 am 12:54 AM
PHP 8

PHP 8 attributes add metadata to code elements in a structured way. 1. They are attached above classes, methods, etc. using #[] syntax, such as #[Route('/home')] to define routes; 2. It is safer than PHPDoc, with type checking and compile-time verification; 3. Custom attributes need to define classes and apply, such as using ReflectionAttribute to create LogExecution log attributes; 4. Commonly used in frameworks to handle routing, verification, ORM mapping and other tasks, improving code readability and separating logical configurations; 5. It can be accessed through reflection, but excessive use should be avoided to avoid affecting code clarity.

What are attributes (annotations) in PHP 8?

PHP 8 introduced a powerful new feature called attributes (also known as annotations in other languages ​​like Java or Python). They provide a structured and reusable way to add metadata to classes, methods, properties, functions, and more — all directly within the code using a clean syntax.

In short, attributes let you "attach" extra information to your code elements without affecting their logic. This can be used for things like routing in frameworks, validation rules, ORM mappings, and more.


What Do Attributes Look Like?

Attributes are written using the #[AttributeName] syntax placed above the element they annotate. Here's a basic example:

 #[Route('/home')]
function home() {
    echo 'Welcome!';
}

In this case, #[Route('/home')] is an attribute that tells some part of the application (like a router) how to handle the home() function.

You can also use multiple attributes:

 #[Cacheable]
#[Method('GET')]
function getData() {
    return fetchData();
}

Each attribute can have arguments passed to it, just like function calls. The exact meaning of those arguments depends on what the attribute does.


How Are Attributes Different from PHPDoc?

Before attributes, developers often used PHPDoc comments to achieve similar goals:

 /**
 * @Route("/home")
 * @Method("GET")
 */
function home() {
    // ...
}

While PHPDoc works, it has limitations:

  • It's not type-safe — everything is a string.
  • There's no enforcement of correct usage.
  • You need to parse the comments manually or with tools.

Attributes solve these issues by being part of the language syntax. They're validated at compile time, support proper typing, and are easier to process programmatically.


How to Define and Use Custom Attributes

Creating your own attribute involves two steps: defining the attribute class and applying it somewhere.

Step 1: Define the Attribute Class

Use the Attribute class provided by PHP (from the ReflectionAttribute API):

 use Attribute;

#[Attribute]
class LogExecution {
    public function __construct(
        public string $message = 'Function executed'
    ) {}
}

This defines an attribute that can be attached to any element.

Step 2: Apply the Attribute

Now apply it to a function:

 #[LogExecution(message: 'User login function')]
function loginUser(string $username) {
    echo "Logging in $username\n";
}

Then, using reflection, you can read the attribute and do something useful — like log the message after the function runs.


Where Are Attributes Commonly Used?

Frameworks and libraries make heavy use of attributes because they allow clean separation between business logic and configuration.

Here are a few common use cases:

  • Routing – Mapping URLs to controller methods
  • Validation – Specifying data constraints for forms or APIs
  • Serialization/Deserialization – Controlling how objects are converted to JSON or XML
  • Dependency Injection – Marking services or injection points
  • ORMs – Mapping database tables and columns to classes and properties

For example, in Symfony or Laravel, you might see something like:

 #[Route('/users/{id}', methods: ['GET'])]
public function show(int $id) {
    return User::find($id);
}

This tells the framework how to route incoming HTTP requests to this method.


A Few Things to Keep in Mind

  • Attributes can target specific code elements using flags when defining them. For example, to only allow usage on functions:

     #[Attribute(Attribute::TARGET_FUNCTION)]
  • You can access attributes via reflection ( ReflectionClass , ReflectionMethod , etc.) to read and act on them.

  • While attributes are very flexible, overusing them can make your code harder to follow if not organized well.

  • Not every project needs custom attributes — but they're super handy in larger applications or frameworks.


  • So yeah, PHP 8's attributes give us a modern, clean, and powerful way to work with metadata in our code. They're not hard to understand once you see how they fit into real-world examples — and they definitely beat parsing comments by hand.

    The above is the detailed content of What are attributes (annotations) in PHP 8?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1535
276
What are named arguments in PHP 8? What are named arguments in PHP 8? Jun 19, 2025 pm 06:05 PM

NamedargumentsinPHP8allowpassingvaluestoafunctionbyspecifyingtheparameternameinsteadofrelyingonparameterorder.1.Theyimprovecodereadabilitybymakingfunctioncallsself-documenting,asseeninexampleslikeresizeImage(width:100,height:50,preserveRatio:true,ups

What is static return type in PHP 8? What is static return type in PHP 8? Jun 24, 2025 am 12:57 AM

ThestaticreturntypeinPHP8meansthemethodisexpectedtoreturnaninstanceoftheclassit'scalledon,includinganychildclass.1.Itenableslatestaticbinding,ensuringthereturnedvaluematchesthecallingclass'stype.2.Comparedtoself,whichalwaysreferstothedefiningclass,an

What is JIT (Just-In-Time) compilation in PHP 8? What is JIT (Just-In-Time) compilation in PHP 8? Jun 20, 2025 am 12:57 AM

JITinPHP8improvesperformancebycompilingfrequentlyexecutedcodeintomachinecodeatruntime.Insteadofinterpretingopcodeseachtime,JITidentifieshotsectionsofcode,compilesthemintonativemachinecode,cachesitforreuse,andreducesinterpretationoverhead.Ithelpsmosti

What are constructor property promotion in PHP 8? What are constructor property promotion in PHP 8? Jun 19, 2025 pm 06:45 PM

ConstructorpropertypromotioninPHP8allowsautomaticcreationandassignmentofclasspropertiesdirectlyfromconstructorparameters.Insteadofmanuallyassigningeachpropertyinsidetheconstructor,developerscanaddanaccessmodifier(public,protected,orprivate)totheparam

What are mixed types in PHP 8? What are mixed types in PHP 8? Jun 21, 2025 am 01:02 AM

PHP8's mixed type allows variables, parameters, or return values ​​to accept any type. 1. Mixed is suitable for scenarios that require high flexibility, such as middleware, dynamic data processing and legacy code integration; 2. It is different from union types because it covers all possible types, including new types in the future; 3. Be cautious when using them to avoid weakening type safety, and it is recommended to explain the expected types in conjunction with phpDoc. The rational use of mixed can improve code expression capabilities while maintaining the advantages of type prompts.

What are match expressions in PHP 8? What are match expressions in PHP 8? Jun 21, 2025 am 01:03 AM

PHP8's match expression provides a cleaner conditional mapping through strict comparison. 1. Use strict equality (===) to avoid type conversion; 2. No break statement is required to prevent accidental penetration; 3. Direct return value can be assigned to variables; 4. Support multi-condition merging and sharing results. Suitable for precise matching and mapping input and output scenarios, such as HTTP status code processing; not suitable for range checks or loose comparisons.

What are the performance improvements in PHP 8 compared to PHP 7? What are the performance improvements in PHP 8 compared to PHP 7? Jun 27, 2025 am 12:51 AM

The performance improvement of PHP8 mainly comes from the newly introduced JIT compiler and Zend engine optimization, but the benefits in actual applications vary by scenario. 1. The JIT compiler compiles some code into machine code at runtime, significantly improving the performance of CLI scripts or long-term APIs, but has limited effect in short-lifetime web requests; 2. OPcache improves and enhances opcode caching and preloading functions, reducing disk I/O and parsing overhead, especially for frameworks such as Laravel or Symfony; 3. Multiple internal optimizations such as more efficient string and array operations, smaller memory usage, etc. Although each improvement is small, it accumulates in small amounts; 4. The actual performance improvement depends on the application scenario, PHP8 can be fast 10 in computing-intensive tasks.

What are attributes (annotations) in PHP 8? What are attributes (annotations) in PHP 8? Jun 22, 2025 am 12:54 AM

PHP8 attributes add metadata to code elements through structured methods. 1. They are attached above classes, methods, etc. using #[] syntax, such as #[Route('/home')] to define routes; 2. It is safer than PHPDoc, with type checking and compile-time verification; 3. Custom attributes need to define classes and apply, such as using ReflectionAttribute to create LogExecution log attributes; 4. Commonly used in frameworks to handle routing, verification, ORM mapping and other tasks, improving code readability and separating logical configurations; 5. It can be accessed through reflection, but excessive use should be avoided to avoid affecting code clarity.

See all articles