2024 年 PHP 日本研討會

ReflectionClass::getAttributes

(PHP 8)

ReflectionClass::getAttributes取得屬性

說明

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

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

參數

name

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

flags

用於決定如何在提供 name 時篩選結果的旗標。

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

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

回傳值

屬性陣列,以 ReflectionAttribute 物件表示。

範例

範例 #1 基本用法

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

#[
Fruit]
#[
Red]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

上述範例將輸出

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

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

<?php
#[Attribute]
class
Fruit {
}

#[
Attribute]
class
Red {
}

#[
Fruit]
#[
Red]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->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 {
}

#[
Fruit]
#[
Red]
class
Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes(Color::class, ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

上述範例將輸出

Array
(
    [0] => Red
)

新增註解

使用者貢獻的註解 2 則註解

sandrenyl at gmail dot com
3 年前
當使用 getAttributes() 方法來擷取基於父類別的屬性時,正確的旗標常數是 ReflectionAttribute::IS_INSTANCEOF(如同 sergiolibe 提到的,等於 2)。

<?php
$reflectionClass
->getAttributes(SomeParentAttribute::class, ReflectionAttribute::IS_INSTANCEOF);
?>
sergiolibe at gmail dot com
3 年前
當使用 getAttributes() 搭配指定的屬性類別和旗標時,旗標 0 將只會返回與指定類別相符的屬性,而 2 則會返回與指定類別及其子類別相符的屬性。
<?php
#[Attribute(\Attribute::TARGET_CLASS)]
class
SomeAttribute {}

#[
Attribute(\Attribute::TARGET_CLASS)]
class
ChildAttribute extends SomeAttribute {}

#[
SomeAttribute]
#[
ChildAttribute]
class
SomeClass {}

$rc = new ReflectionClass(SomeClass::class);

$r_atts = $rc->getAttributes(SomeAttribute::class, 0); // 指定類別 (預設值)
echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;

$r_atts = $rc->getAttributes(SomeAttribute::class, 2); // 指定類別及其子類別
echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;
?>

輸出
["SomeAttribute"]
["SomeAttribute","ChildAttribute"]
To Top