Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Đọc Attributes với Reflection API trong PHP 8

Trong PHP 8, dùng lớp, thuộc tính, hằng số lớp, phương thức, hàm, tham số để truy cập attributes.

Trong PHP 8, Reflection API cung cấp phương thức getAttribute() trên mọi đối tượng Reflection phù hợp.

Phương thức getAttribute() trả về mảng các đối tượng ReflectionAttribute có thể truy vấn tên attribute, tham số và khởi tạo instance của attribute được chỉ định.

Ví dụ - Đọc Attributes với Reflection API trong PHP 8

<?php 
#[Reading]
#[Property(type: 'function', name: 'Student')]
function Student() {
    return "Student";
}
function getAttributes(Reflector $reflection) {
    $attributes = $reflection->getAttributes();
    $finalresult = [];
    foreach ($attributes as $attribute) {
        $finalresult[$attribute->getName()] = $attribute->getArguments();
    }
    return $finalresult;
}
$reflection = new ReflectionFunction("Student");
print_r(getAttributes($reflection));
?>

Kết quả

Array (
    [Reading] => Array ()
    [Property] => Array (
        [type] => function
        [name] => Student
    )
)