目录
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
首页 后端开发 php教程 PHP 8中的属性(注释)是什么?

PHP 8中的属性(注释)是什么?

Jun 22, 2025 am 12:54 AM
PHP 8

PHP 8的attributes通过结构化方式为代码元素添加元数据。1.它们使用#[]语法附加在类、方法等上方,如#[Route('/home')]定义路由;2.与PHPDoc相比更安全,具备类型检查和编译时验证;3.自定义attribute需定义类并应用,例如用ReflectionAttribute创建LogExecution日志属性;4.常见于框架中处理路由、验证、ORM映射等任务,提升了代码可读性和分离逻辑配置;5.可通过反射访问,但应避免过度使用以免影响代码清晰度。

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.

    以上是PHP 8中的属性(注释)是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

PHP 8中的参数是什么? PHP 8中的参数是什么? Jun 19, 2025 pm 06:05 PM

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

PHP 8中的静态返回类型是什么? PHP 8中的静态返回类型是什么? Jun 24, 2025 am 12:57 AM

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

PHP 8中的JIT(即时)汇编是什么? PHP 8中的JIT(即时)汇编是什么? Jun 20, 2025 am 12:57 AM

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

PHP 8中的构造函数促销是什么? PHP 8中的构造函数促销是什么? Jun 19, 2025 pm 06:45 PM

constructorPropertyPromotionInphp8allowsautomaticCreationAndAssignmentOfClassPropertiesDirectlyFromConstructorParameters.insteadofMerallyAssigningEachPropertyInsideTheConstructor,developerersCanaddanAccessmodifier(公共,受保护,Orprivate,Orprivate)totheparam

PHP 8中的匹配表达式是什么? PHP 8中的匹配表达式是什么? Jun 21, 2025 am 01:03 AM

PHP8的match表达式通过严格比较提供更简洁的条件映射。1.使用严格相等(===)避免类型转换;2.无需break语句防止意外贯穿;3.直接返回值可赋给变量;4.支持多条件合并共享结果。适用于精确匹配、映射输入输出场景,如HTTP状态码处理;不适用于范围检查或需要松散比较的情况。

PHP 8中的混合类型是什么? PHP 8中的混合类型是什么? Jun 21, 2025 am 01:02 AM

PHP8的mixed类型允许变量、参数或返回值接受任何类型。1.mixed适用于需要高度灵活性的场景,如中间件、动态数据处理和遗留代码集成;2.它不同于union类型,因涵盖所有可能类型,包括未来新增类型;3.使用时应保持谨慎,避免削弱类型安全性,并建议配合phpDoc说明预期类型。合理使用mixed可在保持类型提示优势的同时提升代码表达能力。

与PHP 7相比,PHP 8的性能改善是什么? 与PHP 7相比,PHP 8的性能改善是什么? Jun 27, 2025 am 12:51 AM

PHP8的性能提升主要来自新引入的JIT编译器和Zend引擎优化,但实际应用中的收益因场景而异。 1.JIT编译器在运行时将部分代码编译为机器码,显着提升CLI脚本或长时API的性能,但在短生命周期的Web请求中作用有限;2.OPcache改进增强了操作码缓存和预加载功能,减少磁盘I/O和解析开销,尤其利于Laravel或Symfony等框架;3.多项内部优化如更高效的字符串和数组操作、更小的内存占用等,虽每次提升微小但积少成多;4.实际性能提升视应用场景而定,在计算密集型任务中PHP8可快10–

PHP 8中的属性(注释)是什么? PHP 8中的属性(注释)是什么? Jun 22, 2025 am 12:54 AM

PHP8的attributes通过结构化方式为代码元素添加元数据。1.它们使用#[]语法附加在类、方法等上方,如#[Route('/home')]定义路由;2.与PHPDoc相比更安全,具备类型检查和编译时验证;3.自定义attribute需定义类并应用,例如用ReflectionAttribute创建LogExecution日志属性;4.常见于框架中处理路由、验证、ORM映射等任务,提升了代码可读性和分离逻辑配置;5.可通过反射访问,但应避免过度使用以免影响代码清晰度。

See all articles