Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

การอ่าน Attributes ด้วย Reflection API ใน PHP 8

ใน PHP 8 เราใช้คลาส พรอเพอร์ตี้ และค่าคงที่ของคลาส เมธอด ฟังก์ชัน พารามิเตอร์ เพื่อเข้าถึง attributes

ใน PHP 8 Reflection API ส่งมอบเมธอด getAttribute() บนทุก Reflection object ที่ตรงกัน

เมธอด getAttribute() คืนค่าอาร์เรย์ของภาพประกอบ ReflectionAttribute ที่สามารถถามชื่อ attribute อาร์กิวเมนต์ และสร้าง instance ของ attribute ที่ระบุได้

ตัวอย่าง - อ่าน Attributes ด้วย Reflection API ใน 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)); 
?>

ผลลัพธ์

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