最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
PHP的反射动态获取类方法与属性和参数代码示例
时间:2022-06-24 14:34:20 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下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
相关文章
- 无尽花界诸神角色图鉴 无尽花界阵营角色详细介绍 05-08
- 驯龙之旅兑换码大全 驯龙之旅最新可用礼包码汇总 05-08
- 曲奇云盘怎么保存别人分享的文件 05-08
- 末世避难所手游新手入门指南 末世避难所手游零基础快速上手教程 05-08
- 六道轮回手游上线时间揭晓 六道轮回手游正式开服日期分享 05-08
- 无限暖暖埋骨地10个冥想点位一览 05-08