注解语法

注解语法包含以下几部分。 首先,注解声明总是以 #[ 开头,以 ] 结尾来包围。 内部则是一个或以逗号包含的多个注解。 注解的名称按 使用命名空间:基础 章节中描述,可以是非限定、限定、完全限定的名称。 注解的参数是可以选的,以常见的括号()包围。 注解的参数只能是字面值或者常量表达式。 它同时接受位置参数和命名参数两种语法。

通过反射 API 请求注解实例时,注解的名称会被解析到一个类,注解的参数则传入该类的构造器中。 因此每个注解都需要引入一个类。

示例 #1 注解语法

<?php
// a.php
namespace MyExample;

use
Attribute;

#[
Attribute]
class
MyAttribute
{
const
VALUE = 'value';

private
$value;

public function
__construct($value = null)
{
$this->value = $value;
}
}

// 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
{
}
添加备注

用户贡献的备注 1 note

up
3
yarns dot purport0n at icloud dot com
1 year ago
It wasn't obvious to me for a while but you can subclass attributeshttps://3v4l.org/TrMTe<?php#[Attribute(Attribute::TARGET_PROPERTY)]class PropertyAttributes {    public function __construct(        public readonly ?string $name = null,        public readonly ?string $label = null,    ) {} }#[Attribute(Attribute::TARGET_PROPERTY)]class IntegerPropertyAttributes extends PropertyAttributes {    public function __construct(        ?string $name = null,        ?string $label = null,        public readonly ?int $default = null,        public readonly ?int $min = null,        public readonly ?int $max = null,        public readonly ?int $step = null,    ) {        parent::__construct($name, $label);    } }#[Attribute(Attribute::TARGET_PROPERTY)]class FloatPropertyAttributes extends PropertyAttributes {    public function __construct(        ?string $name = null,        ?string $label = null,        public readonly ?float $default = null,        public readonly ?float $min = null,        public readonly ?float $max = null,    ) {        parent::__construct($name, $label);    } }class MyClass {     #[IntegerPropertyAttributes('prop', 'property: ', 5, 0, 10, 1)]     public int $prop; }$refl = new ReflectionProperty('MyClass', 'prop');$attributes = $refl->getAttributes();    foreach ($attributes as $attribute) {       var_dump($attribute->getName());       var_dump($attribute->getArguments());       var_dump($attribute->newInstance());    }?>
To Top