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

การอ่านคุณสมบัติด้วย Reflection API ใน PHP 8


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

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

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

ตัวอย่าง – การอ่านแอตทริบิวต์ด้วย 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
   )
)