PHP 8 Attributes 简介与传统注释对比
PHP 8 的 Alpha 版本即将发布,其中包含多项新特性。尽管 JIT(即时编译)自 2013 年起便备受关注,历经无数挫折与尝试后终于到来,但本文暂不讨论该话题。
关于 JIT 的深入解析,如《深入理解 PHP 8 之 JIT》系列内容,将在 PHP 8 正式发布后另行撰写。
今日重点探讨 Attributes 特性。近期许多社群转发了一篇题为《理解 PHP 8 中的 Attributes》的文章,该文疑似直接翻译自英文资料,表述晦涩难懂,导致许多读者感到困惑,无法理解其核心含义。
鉴于此,本文旨在用通俗易懂的方式,简要说明 Attributes 的概念及其工作原理。
在介绍注解之前,需先回顾传统的注释机制。在以往的 PHP 项目中,常见类似 @param 和 @see 的标记:
/**
* @param Foo $argument
* @see https:/xxxxxxxx/xxxx/xxx.html
*/
function dummy($Foo) {}
这被称为注释(DocBlock)。在旧版 PHP 中,@param 和 @see 等标记并无实际语义,整段注释仅作为名为 doc_comment 的字符串保存于函数或方法中。
若要解析这些注释的含义,需设计特定语法规则(如识别 @+name 格式),并通过手动分析字符串来提取信息。
例如,若要从上述注释中提取 @see 的信息,需进行如下字符串处理:
$ref = new ReflectionFunction("dummy");
$doc = $ref->getDocComment();
$see = substr($doc, strpos($doc, "@see") + strlen("@see "));
这种处理方式较为繁琐,且容易因字符串操作不当而出错。
Attributes 的本质是将非结构化的“注释”升级为支持格式化内容的“注解”。
以之前的例子为例,使用 Attributes 后的写法如下:
<?php
<>
<>
function dummy($argument) {}
无需纠结其具体业务意义,从功能角度看,现在可以通过 Reflection API 直接获取这段格式化的注解。例如,获取 See 注解的代码如下:
$ref = new ReflectionFunction("dummy");
var_dump($ref->getAttributes("See")[0]->getName());
var_dump($ref->getAttributes("See")[0]->getArguments());
执行后将输出:
string(3) "See"
array(1) {
[0]=>
string(30) "https://xxxxxxxx/xxxx/xxx.html"
}
此外,还有更高级的用法:定义所谓的“注解类”。
<?php
<>
class MyAttribute {
public function __construct($name, $value) {
var_dump($name);
var_dumP($value);
}
}
随后可以编写类似以下的代码,注意其中的 newInstance 调用:
<>
function dummy($argument) {
}
$ref = new ReflectionFunction("dummy");
$ref->getAttributes("MyAttribute")[0]->newInstance();
运行该代码时,会触发 MyAttribute 类的 __construct 方法,传递的参数即为构造时指定的值(如 “See” 和 “https://xxx”)。
简而言之,你可以将注解“实例化”,基于此能力实现“注释即配置”的设计模式。
总结 Attributes 的基本写法形式如下:
<>
<>
<>
随后可通过 PHP 的 Reflection 系列方法,调用 getAttributes("Name") 获取对应注解。进一步可通过返回对象的 getName() 方法获取名称,通过 getArguments() 方法获取括号内的参数。
更进一步,如果 Name 是自定义的、带有 PHP Attributes 支持的类,还可调用 newInstance() 方法,实现类似 new Name(Arguments) 的实例化调用。
或许有人会问:这究竟有何实际用途?
坦白说,我对大多数新特性持保留态度,但 Attributes 确实具备独特的实用价值。
以上为 PHP 8 新特性 Attributes 的详细解析,更多相关资料请关注本站后续文章。