php的反射

我们可以在PHP运行时,通过PHP的反射动态的获取类的方法、属性、参数等详细信息。
 
用途:插件的设计,文档的自动生成,扩充PHP语言。
<?php
class Person {
    const weightUnit = 'kg';
    const heightUnit = 'cm';
    public $name = 'test';
    public $age = 1;
    public function say($msg = '') {
        echo $msg;
    }
}

$p = new Person ();
// 普通的实例化对象,调用方法
$p->say ( 'hello' );

// 创建一个Person的反射类
$rp = new ReflectionClass ( 'Person' );

// 通过ReflectionClass的方法来获取类的详细信息

// 获取常量
echo $rp->getConstant ( 'weightUnit' );
// 获取类中已定义的常量
var_dump ( $rp->getConstants () );

// 获取属性,返回的是一个ReflectionProperty类
$propName = $rp->getProperty ( 'name' );
echo $propName->getName(), ':', $propName->getValue ( new Person () );

// 获取类中已定义的一组属性
$propArr = $rp->getProperties ();
foreach ( $propArr as $obj ) {
    echo $obj->getName (), ':', $obj->getValue ( new Person () );
}

//获取方法,返回的是一个ReflectionMethod类
$sayMetd = $rp->getMethod('say');
if($sayMetd->isPublic() && !$sayMetd->isAbstract()) {
    $sayMetd->invoke(new Person(), 'hehe');
    $sayMetd->invokeArgs(new Person(), array('hehe'));
}

//获取类中已定义的一组方法,可以过滤不需要的方法
$metds = $rp->getMethods();

//获取命名空间
echo $rp->getNamespaceName();

//判断一个方法是否定义
if($rp->hasMethod('say')) {
    echo 'say has';
}

//判断一个属性是否定义
if($rp->hasProperty('name')) {
    echo 'name has';
}
原文地址:https://www.cnblogs.com/jkko123/p/6294627.html