1.注解声明
注解的本质是类。
要想声明某个类为注解,只需要通过 use
语句从全局命名空间引入 #[Attribute]
注解。
<?php
// a.php
namespace MyExample;
use Attribute;
#[Attribute]
class MyAttribute
{
const VALUE = 'value';
private $value;
public function __construct($value = null)
{
$this->value = $value;
}
}
如果想要限定注解只能被哪些目标使用,可以添加如下限定。
<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class MyAttribute
{
}
限定 | 目标 |
Attribute::TARGET_CLASS | 类 |
Attribute::TARGET_FUNCTION | 函数 |
Attribute::TARGET_METHOD | 方法 |
Attribute::TARGET_PROPERTY | 属性 |
Attribute::TARGET_CLASS_CONSTANT | 类常量 |
Attribute::TARGET_PARAMETER | 参数 |
Attribute::TARGET_ALL | 所有 |
Attribute::IS_REPEATABLE | 允许注解在声明中出现多次 |
2.调用注解
注解总是以 #[
开头,以 ]
结尾来包围。
方括号[]
内可以是一个或多个注解(以逗号分隔)。
注解名称可以是非限定、限定、完全限定的名称。
注解的参数是非必须的。如果有参数,以常见的括号()
包围。注解的参数可以是字面值或者常量表达式。它同时接受按位置传递和按命名传递两种参数传递方式。
当通过反射 API注解的实例被请求时,注解的名称会被解析到一个类名,注解的参数则被传入该类的构造器对应参数中。 因此每个注解都需要引入一个类。
<?php
// b.php
namespace Another;
use MyExample\MyAttribute;
#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}
#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}
原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/php/phplang/9277.html