php – ReflectionClass 反射類別,讀取指定類別的資料

要讀取某個class內有哪些方法(method)或是屬性的時候,我們可以透過這支 ReflectionClass 類別來做到;雖然在 function 的 get_class_methods() 也可以取得方法列表,但是對於方法的屬性是public protected private 我們是無法得知的。如果只是想知道類別有哪些方法,用 get_class_methods() 就好。

$relflection = new ReflectionClass('Layout'); //輸入你要查找的類別名稱,如我要查找 Layout 類別

若要列出 public 的方法

print_r($relflection->getMethods(ReflectionMethod::IS_PUBLIC));

可透過參數來過濾,ReflectionMethod::IS_PUBLIC 即可。其他選用的參數可參考官網介紹的類別:ReflectionMethod

可以使用這些來篩選

const integer IS_STATIC = 1 ;
const integer IS_PUBLIC = 256 ;
const integer IS_PROTECTED = 512 ;
const integer IS_PRIVATE = 1024 ;
const integer IS_ABSTRACT = 2 ;
const integer IS_FINAL = 4 ;

所以,使用 IS_PUBLIC 會列出如

    [0] => ReflectionMethod Object
        (
            [name] => __construct //建構函數也會顯示
            [class] => Layout //屬於哪個類別
        )

    [1] => ReflectionMethod Object
        (
            [name] => project
            [class] => Layout
        )

    [2] => ReflectionMethod Object
        (
            [name] => index
            [class] => Layout
        )

    [3] => ReflectionMethod Object
        (
            [name] => contact
            [class] => Layout
        )

    [4] => ReflectionMethod Object
        (
            [name] => news
            [class] => Layout
        )

    [5] => ReflectionMethod Object
        (
            [name] => get_instance //像這個方法是屬於 CI_Controller
            [class] => CI_Controller // 為什麼不是 Layout 呢?這是因為我的 Layout 繼承 CI_Controller 類別,所以父類別的 public 也會顯示喔
        )

 

 

發表迴響