使用反射 API 在 PHP 8 中讀取屬性


在 PHP 8 中,我們使用類、屬性、及類常量、方法、函式、引數來訪問屬性。

在 PHP 8 中,反射 API在每個匹配的反射物件上提供了 getAttribute() 方法。

getAttribute() 方法返回一個反射屬性說明的陣列,該陣列可以被詢問屬性名稱、引數並例項化表示屬性的例項。

示例 − 在 PHP 8 中使用反射 API 讀取屬性

<?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
   )
)

更新於:01-Apr-2021

591 次瀏覽

開啟您的 職業

完成課程取得認證

立即開始
廣告
© . All rights reserved.