PHP8新特性----注解

说注解之前,先说说以前的注释,我们经常会在PHP的项目中,看到的一个东西,类似如下的@param 和 @see :

/**
 * @param Foo $argument
 * @see https:/xxxxxxxx/xxxx/xxx.html
 */    
 function dummy($Foo) {}

这个叫做注释,对于以前的PHP来说,注释中的@param和@see毫无意义,整个这一段会保存为一个函数/方法的一个叫做doc_comment的字符串。

如果我们要分析这段注释的含义,我们需要通过设计一些特定的语法,就比如栗子中的@+name, 类似@param一样, 然后自己分析这段字符串,来提取对应的信息。

比如我们要获取See这个注释的信息,我们需要做类似:

$ref = new ReflectionFunction("dummy");
$doc = $ref->getDocComment();
$see = substr($doc, strpos($doc, "@see") + strlen("@see "));

这样的字符串处理,相对比较麻烦,也比较容易出错。

而Attributes呢,其实就是把“注释”升级为支持格式化内容的“注解”

例如:

#[
 Params("Foo", "argument"),
 See("https://xxxxxxxx/xxxx/xxx.html")
]
function dummy($argument) {}


$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"
}
*/

从功能上来说,现在你就可以通过Reflection来获取这段格式化的注解了。

当然,还有稍微高级一点的用法,就是你可以定义一个所谓的“注解类”:

<?php
#[Attribute(Attribute::TARGET_FUNCTION)]
class MyAttribute {
     public function __construct($name, $value) {
          var_dump($name);
          var_dump($value);
     }
}

#[MyAttribute("See", "https://xxxxxxxx/xxxx/xxx.html")]
function dummy($argument) {}

$ref = new ReflectionFunction("dummy");
// 注意newInstance的调用
$ref->getAttributes("MyAttribute")[0]->newInstance();

总结

Attributes的写法,就是形式如下:

#[Name]
#[Name(Arguments)]
#[Name(Argunment1, Arguments2, ArgumentN)]
 
#[Name1(Argument), Name2(Argument), Name3(Argument)]

然后你就可以通过PHP的Reflection系列的方法,根据getAttributes("Name")获取对应的注解, 进一步你可以通过调用返回的注解的getName方法获取名字,getArguments方法获取括号中的Arguments。

再进一步,如果Name是一个你自己定义的注解类,通过#[Attribute(Attribute::TARGET_FUNCTION)], 或者:

TARGET_CLASS    //类的注解类
TARGET_FUNCTION //函数注解类
TARGET_METHOD   //方法注解类
TARGET_PROPERTY //属性注解类
TARGET_CLASS_CONSTANT //类常量注解类
TARGET_PARAMETER //参数注解类
TARGET_ALL 

来表明注解类应用的目标类型,然后你就可以调用newInstance方法,实现类似"new Name(Arguments)"的调用

posted @ 2021-03-14 08:12  佳星辰  阅读(599)  评论(0编辑  收藏  举报