本文实例讲述了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
新闻热点
疑难解答