关于类的反射

关于类的反射


 

类的反射:通过实例化后的对象,获得所属的类、这个类有哪些属性、方法等信息。


 

反射API:

class User{
    public $name;
    private $age;
    static $gender;

    public function __construct($name='',$age=0,$gender='保密'){
        $this->name = $name;
        $this->age = $age;
        self::$gender = $gender;//注意,这里self::后的变量要写$符号
    }

    public function getInfo(){
        return '姓名:'.$this->name.',年龄:'.$this->age;
    }

}


$student = new User('zhang_san',12);


$reflect = new ReflectionObject($student);
var_dump($reflect);
//输出:
//object(ReflectionObject)[2]
//  public 'name' => string 'User' (length=4)

//获取$student这个对象所属的类
var_dump(get_class($student));
//输出:string 'User'

//获取所属的【类的属性】列表
$props = $reflect->getProperties();
foreach ($props as $value) {
    //打印访问权限
    echo $value->isStatic()?'static ':'';
    echo $value->isPublic()?'public':'';
    echo $value->isPrivate()?'private':'';
    echo $value->isProtected()?'protected':'';
    //打印属性名字
    echo ' ' . $value->getName();
    echo '<br>';
}
//输出结果:
// public name
// private age
// static public gender


//获取所属的【类的方法】列表
$methods= $reflect->getMethods();
foreach ($methods as $value) {
    //打印访问权限
    echo $value->isStatic()?'static ':'';
    echo $value->isPublic()?'public':'';
    echo $value->isPrivate()?'private':'';
    echo $value->isProtected()?'protected':'';
    echo $value->isAbstract()?'abstract':'';

    //打印属性名字
    echo ' ' . $value->getName();
    echo '<br>';
}
//输出结果:
//public __construct
//public getInfo

扩展知识:(关于class的函数)

var_dump(get_class($student));
//输出:string 'User'

var_dump(get_object_vars($student));
// array (size=1)
//    'name' => string 'zhang_san'

var_dump(get_class_vars(get_class($student)));
// array (size=2)
//    'name' => null
//    'gender' => string '保密'

var_dump(get_class_methods(get_class($student)));
// array (size=2)
//    0 => string '__construct'
//    1 => string 'getInfo'

 

posted @ 2020-09-24 09:15  学知无涯  阅读(191)  评论(0编辑  收藏  举报