2024 年 PHP 日本研討會

ReflectionClassConstant::getAttributes

(PHP 8)

ReflectionClassConstant::getAttributes取得屬性

說明

public ReflectionClassConstant::getAttributes(?string $name = null, int $flags = 0): array

ReflectionAttribute 陣列的形式返回在此類別常數上宣告的所有屬性。

參數

名稱

篩選結果,僅包含與此類別名稱相符的屬性的 ReflectionAttribute 實例。

flags(旗標)

用於決定如何在提供 name(名稱)參數時篩選結果的旗標。

預設值為 0,這將只會傳回類別為 name 的屬性結果。

另一個可用的選項是使用 ReflectionAttribute::IS_INSTANCEOF,它將改用 instanceof 進行篩選。

回傳值

屬性陣列,以 ReflectionAttribute 物件呈現。

範例

範例 #1 基本用法

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

class
Basket {
#[
Fruit]
#[
Red]
public const
APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

上述範例將輸出

Array
(
    [0] => Fruit
    [1] => Red
)

範例 #2 透過類別名稱篩選結果

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

class
Basket {
#[
Fruit]
#[
Red]
public const
APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

上述範例將輸出

Array
(
    [0] => Fruit
)

範例 #3 使用繼承,透過類別名稱篩選結果

<?php
interface Color {
}

#[
Attribute]
class
Fruit {
}

#[
Attribute]
class
Red implements Color {
}

class
Basket {
#[
Fruit]
#[
Red]
public const
APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

上述範例將輸出

Array
(
    [0] => Red
)

新增註釋

使用者貢獻的註釋

此頁面沒有使用者貢獻的註釋。
To Top