W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
雖然沒有嚴(yán)格要求,推薦為每個注解創(chuàng)建一個實際的類。 在這個最簡單的例子中,通過 use 語法從全局命名空間引入 #[Attribute] 注解所需要全空的類。
示例 #1 簡單的 Attribute 類
<?php
namespace Example;
use Attribute;
#[Attribute]
class MyAttribute
{
}
要限制指定注解的聲明類型,可為 #[Attribute] 注解第一個參數(shù)傳入字節(jié)位掩碼設(shè)置。
示例 #2 目標(biāo)限定使用的注解
<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class MyAttribute
{
}
在另一個類型中聲明 MyAttribute 會在調(diào)用 ReflectionAttribute::newInstance() 時拋出異常。
可以指定以下目標(biāo):
注解在每個聲明中默認(rèn)情況下只能使用一次。 如果需要重復(fù),可以在 #[Attribute] 聲明中設(shè)置字節(jié)位掩碼。
示例 #3 使用 IS_REPEATABLE 允許注解在聲明中出現(xiàn)多次
<?php
namespace Example;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::IS_REPEATABLE)]
class MyAttribute
{
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: