一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

PHP的反射动态获取类方法与属性和参数代码示例

时间:2020-03-05 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下PHP的反射动态获取类方法与属性和参数代码示例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

我们可以在PHP运行时,通过PHP的反射动态的获取类的方法、属性、参数等详细信息。

用途:插件的设计,文档的自动生成,扩充PHP语言。

say ( 'hello' );
echo "
"; // 创建一个Person的反射类 $rp = new ReflectionClass ( 'Person' ); // 通过ReflectionClass的方法来获取类的详细信息 // 获取常量 echo $rp->getConstant ( 'weightUnit' ); echo "
"; // 获取类中已定义的常量 var_dump ( $rp->getConstants () ); // 获取属性,返回的是一个ReflectionProperty类 $propName = $rp->getProperty ( 'name' ); echo $propName->getName(), ':', $propName->getValue ( new Person () ); echo "
"; // 获取类中已定义的一组属性 $propArr = $rp->getProperties (); foreach ( $propArr as $obj ) { echo $obj->getName (), ':', $obj->getValue ( new Person () ); } echo "
"; //获取方法,返回的是一个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(); echo "
"; //判断一个方法是否定义 if($rp->hasMethod('say')) { echo 'say has'; } echo "
"; //判断一个属性是否定义 if($rp->hasProperty('name')) { echo 'name has'; }

运行结果:

hello

kg

array(2) { ["weightUnit"]=> string(2) "kg" ["heightUnit"]=> string(2) "cm" } name:test

name:testage:1

hehehehe

say has

name has

热门栏目