這篇文章主要介紹了PHP基於反射獲取一個類別中所有的方法,結合實例形式較為詳細的分析了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 : 0 REDIS_STRING : 1 REDIS_SET : 2 REDIS_LIST : 3 REDIS_ZSET : 4 REDIS_HASH : 5 ATOMIC : 0 MULTI : 1 PIPELINE : 2 OPT_SERIALIZER : 1 OPT_PREFIX : 2 OPT_READ_TIMEOUT : 3 SERIALIZER_NONE : 0 SERIALIZER_PHP : 1 OPT_SCAN : 4 SCAN_RETRY : 1 SCAN_NORETRY : 0 AFTER : after BEFORE : before --------------------props:-------------- -----------------methods:--------------- __construct __destruct connect pconnect close ping echo get set setex psetex setnx getSet randomKey renameKey renameNx getMultiple exists delete incr incrBy incrByFloat decr decrBy type append getRange setRange getBit setBit strlen getKeys sort sortAsc sortAscAlpha sortDesc sortDescAlpha lPush rPush lPushx rPushx lPop rPop blPop brPop lSize lRemove listTrim lGet lGetRange lSet lInsert sAdd sSize sRemove sMove sPop sRandMember sContains sMembers sInter sInterStore sUnion sUnionStore sDiff sDiffStore setTimeout save bgSave lastSave flushDB flushAll dbSize auth ttl pttl persist info resetStat select move bgrewriteaof slaveof object bitop bitcount bitpos mset msetnx rpoplpush brpoplpush zAdd zDelete zRange zReverseRange zRangeByScore zRevRangeByScore zRangeByLex zCount zDeleteRangeByScore zDeleteRangeByRank zCard zScore zRank zRevRank zInter zUnion zIncrBy expireAt pexpire pexpireAt hGet hSet hSetNx hDel hLen hKeys hVals hGetAll hExists hIncrBy hIncrByFloat hMset hMget multi discard exec pipeline watch unwatch publish subscribe psubscribe unsubscribe punsubscribe time eval evalsha script debug dump restore migrate getLastError clearLastError _prefix _serialize _unserialize client scan hscan zscan sscan pfadd pfcount pfmerge getOption setOption config slowlog rawCommand getHost getPort getDBNum getTimeout getReadTimeout getPersistentID getAuth isConnected getMode wait pubsub open popen lLen sGetMembers mget expire zunionstore zinterstore zRemove zRem zRemoveRangeByScore zRemRangeByScore zRemRangeByRank zSize substr rename del keys lrem ltrim lindex lrange scard srem sismember zrevrange sendEcho evaluate evaluateSha
#進一步當我們想要知道具體一個方法怎麼使用,有哪些參數時,我們可以對這個方法進行進一步的反射,以上例中的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 ] } }
#
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中文網其他相關文章!