通过反射机制获取PHP类的全部要领

时间:2014-02-15所属栏目: PHP/PHP框架 来源: 未知 热度:

想要获取一个PHP类的要领,各人也许很天然的想到了get_class_methods(),可手册中并没声名此函数返回的只是public范例的要领。
假如想要获取到包罗私有和掩护的全部要领,那必要用到PHP中反射类,照旧通过例子来声名吧。

<?php
class Foo
{
    private function priFunc(){}
    protected function proFunc(){}
    public function pubFunc(){}
}

function get_class_all_methods($class){
    $r = new ReflectionClass($class);
    foreach($r->getMethods() as $key=>$methodObj){
        if($methodObj->isPrivate())
            $methods[$key]['type'] = 'private';
        elseif($methodObj->isProtected())
            $methods[$key]['type'] = 'protected';
        else
            $methods[$key]['type'] = 'public';
        $methods[$key]['name'] = $methodObj->name;
        $methods[$key]['class'] = $methodObj->class;
    }
    return $methods;
}

$methods = get_class_all_methods('Foo');
var_dump($methods);

功效:

array(3) {
  [0]=>
  array(3) {
    ["type"]=>
    string(7) "private"
    ["name"]=>
    string(7) "priFunc"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  array(3) {
    ["type"]=>
    string(9) "protected"
    ["name"]=>
    string(7) "proFunc"
    ["class"]=>
    string(3) "Foo"
  }
  [2]=>
  array(3) {
    ["type"]=>
    string(6) "public"
    ["name"]=>
    string(7) "pubFunc"
    ["class"]=>
    string(3) "Foo"
  }
}
标签:get_class_all_methods, get_class_methods, php, ReflectionClass
标签:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)