注解語(yǔ)法

注解語(yǔ)法包含以下幾部分。 首先,注解聲明總是以 #[ 開頭,以 ] 結(jié)尾來(lái)包圍。 內(nèi)部則是一個(gè)或以逗號(hào)包含的多個(gè)注解。 注解的名稱按 使用命名空間:基礎(chǔ) 章節(jié)中描述,可以是非限定、限定、完全限定的名稱。 注解的參數(shù)是可以選的,以常見的括號(hào)()包圍。 注解的參數(shù)可以是字面值或者常量表達(dá)式。 它同時(shí)接受位置參數(shù)和命名參數(shù)兩種語(yǔ)法。

通過(guò)反射 API 請(qǐng)求注解實(shí)例時(shí),注解的名稱會(huì)被解析到一個(gè)類,注解的參數(shù)則傳入該類的構(gòu)造器中。 因此每個(gè)注解都需要引入一個(gè)類。

示例 #1 注解語(yǔ)法

<?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
{
}