PHP基于反射获取一个类中所有的方法

时间:2021-05-26

本文实例讲述了PHP基于反射获取一个类中所有的方法。分享给大家供大家参考,具体如下:

当我们使用一个类时既没有源码也没有文档时(尤其是php扩展提供的类,比如mysqli,Redis类),我们该怎么知道这个类中提供了哪些方法,以及每个方法该怎么使用呢,此时就该PHP中强大的反射登场了,下面以Redis扩展为例用代码演示:

<?php$ref = new ReflectionClass('Redis');$consts = $ref->getConstants(); //返回所有常量名和值echo "----------------consts:---------------" . PHP_EOL;foreach ($consts as $key => $val){ echo "$key : $val" . PHP_EOL;}$props = $ref->getDefaultProperties(); //返回类中所有属性echo "--------------------props:--------------" . PHP_EOL . PHP_EOL;foreach ($props as $key => $val){ echo "$key : $val" . PHP_EOL; // 属性名和属性值}$methods = $ref->getMethods(); //返回类中所有方法echo "-----------------methods:---------------" . PHP_EOL . PHP_EOL;foreach ($methods as $method){ echo $method->getName() . PHP_EOL;}

返回结果:

----------------consts:---------------REDIS_NOT_FOUND : 0REDIS_STRING : 1REDIS_SET : 2REDIS_LIST : 3REDIS_ZSET : 4REDIS_HASH : 5ATOMIC : 0MULTI : 1PIPELINE : 2OPT_SERIALIZER : 1OPT_PREFIX : 2OPT_READ_TIMEOUT : 3SERIALIZER_NONE : 0SERIALIZER_PHP : 1OPT_SCAN : 4SCAN_RETRY : 1SCAN_NORETRY : 0AFTER : afterBEFORE : before--------------------props:-------------------------------methods:---------------__construct__destructconnectpconnectclosepingechogetsetsetexpsetexsetnxgetSetrandomKeyrenameKeyrenameNxgetMultipleexistsdeleteincrincrByincrByFloatdecrdecrBytypeappendgetRangesetRangegetBitsetBitstrlengetKeyssortsortAscsortAscAlphasortDescsortDescAlphalPushrPushlPushxrPushxlPoprPopblPopbrPoplSizelRemovelistTrimlGetlGetRangelSetlInsertsAddsSizesRemovesMovesPopsRandMembersContainssMemberssIntersInterStoresUnionsUnionStoresDiffsDiffStoresetTimeoutsavebgSavelastSaveflushDBflushAlldbSizeauthttlpttlpersistinforesetStatselectmovebgrewriteaofslaveofobjectbitopbitcountbitposmsetmsetnxrpoplpushbrpoplpushzAddzDeletezRangezReverseRangezRangeByScorezRevRangeByScorezRangeByLexzCountzDeleteRangeByScorezDeleteRangeByRankzCardzScorezRankzRevRankzInterzUnionzIncrByexpireAtpexpirepexpireAthGethSethSetNxhDelhLenhKeyshValshGetAllhExistshIncrByhIncrByFloathMsethMgetmultidiscardexecpipelinewatchunwatchpublishsubscribepsubscribeunsubscribepunsubscribetimeevalevalshascriptdebugdumprestoremigrategetLastErrorclearLastError_prefix_serialize_unserializeclientscanhscanzscansscanpfaddpfcountpfmergegetOptionsetOptionconfigslowlograwCommandgetHostgetPortgetDBNumgetTimeoutgetReadTimeoutgetPersistentIDgetAuthisConnectedgetModewaitpubsubopenpopenlLensGetMembersmgetexpirezunionstorezinterstorezRemovezRemzRemoveRangeByScorezRemRangeByScorezRemRangeByRankzSizesubstrrenamedelkeyslremltrimlindexlrangescardsremsismemberzrevrangesendEchoevaluateevaluateSha

进一步当我们想要知道具体一个方法怎么使用,有哪些参数时,我们可以对这个方法进行进一步的反射,以上例中的bitpos方法为例(文档中并没有介绍该方法的使用)

echo '---------------------params-----------------------' . PHP_EOL . PHP_EOL;$reflectMethod = $ref->getMethod('bitpos'); //传入方法名即可echo $reflectMethod; // 会调用$reflectMethod->__toString() 返回可打印的形式;

打印结果:

---------------------params-----------------------Method [ <internal:redis> public method bitpos ] {}

并没有看到需要参数,可能与该方法的具体实现有关,具体原因只能去看redis扩展的代码实现,正常情况下应该是返回如下的形式,以mysqli的select_db方法为例:

$ref = new ReflectionClass('mysqli');echo '---------------------params-----------------------' . PHP_EOL . PHP_EOL;$reflectMethod = $ref->getMethod('select_db'); //传入方法名即可echo $reflectMethod; // 会调用$reflectMethod->__toString() 返回可打印的形式;---------------------params-----------------------Method [ <internal:mysqli> public method select_db ] { - Parameters [1] { Parameter #0 [ <required> $database ] }}

这时就没办法了 我们只能靠对redis的理解以及参考相似方法来使用了,比如bitop

public function bitOp( $operation, $retKey, ...$keys) {}

贴下最终的方法调用

$redis = new Redis();$redis->connect('127.0.0.1');$redis->setBit('bit', 15, 1);echo 'bitpos: ' . $redis->bitpos('bit', 1) . PHP_EOL; //bitpos: 15$redis->close();

是不是很有趣呢!

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章