PHP Conference Japan 2024

ReflectionProperty::getAttributes

(PHP 8)

ReflectionProperty::getAttributes取得屬性

說明

public ReflectionProperty::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 {
}

class
Basket {
#[
Fruit]
#[
Red]
public
string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->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
string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->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
string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上範例將輸出

Array
(
    [0] => Red
)

新增註釋

使用者貢獻的註釋

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