凌的博客

您现在的位置是: 首页 > 学无止境 > PHP > 

PHP

php ReflectionClass 获取private,protected,public方法

php
2019-10-02 PHP 1198
class demo
{
    public static $_instance = null;
    private $name;
 
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
 
            self::$_instance = new self;
        }
        return self::$_instance;
    }
 
    public function __call($name, $argu)
    {
        echo str_repeat($name, $argu[0]);
        /**这据说是腾讯的面试题要求输出类似:
         * $obj->shout(1);//shout
         * $obj->sleep(2);//sleepsleep
         **/
 
    }
 
    public function setname($value)
    {
        $this->name = $value;
    }
 
    public function getname()
    {
        return $this->name;
    }
 
    protected function hello()
    {
        echo 'hello';
    }
 
    private function prifunc()
    {
        echo 'pir';
    }
 
}
 
$b = demo::getInstance();
 
// var_dump(get_class_methods($b));// 这样拿不到上面demo类的hello和prifunc方法,只能拿到public的
 
$b->setname('tb');// 先设置下名字
// echo $b->getname();// 拿到名字,这里举例是为了说明如果反射类,是直接不能拿到上一行的setname的值得,至于如何拿到,目前我不知道。。
$class = new ReflectionClass('demo');//那我们来个反射
// var_dump($class->getMethods());// 获取反射demo对象类的所有方法,包括public private protected
// 下面这个方法可以规范输出下
function getobjallmethods($obj)
{
    $class = new ReflectionClass($obj);
    foreach ($class->getMethods() as $key => $methodType) {
        if ($methodType->isPrivate()) {
            $allmethods[$key]['type'] = 'private';
        } elseif ($methodType->isProtected()) {
            $allmethods[$key]['type'] = 'protected';
        } else {
            $allmethods[$key]['type'] = 'public';
        }
        $allmethods[$key]['name'] = $methodType->name;
        $allmethods[$key]['class'] = $methodType->class;
    }
    return $allmethods;
}
 
$r = getobjallmethods('demo');
// var_dump($r);
 
$properities = $class->getProperties();
$classd = $class->newInstance();//实例化
// var_dump($class);
// echo $classd->hello();
$classd->setname('tb2');//如果不在此设置拿不到上一个this的name值得
echo $classd->getname();// 如果没有上门那句tb2,这句会为空
$method = $class->getmethod('getname');
// $method=$class->getmethod('hello');
echo $method->invoke($classd);//参数是类,执行这个method方法,感觉有点倒装的意思,比较官方的说法是:反射类方法对象的调用方式


文章评论

0条评论