歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> PHP - ReflectorClass 反射類的作用

PHP - ReflectorClass 反射類的作用

日期:2017/3/1 10:17:20   编辑:Linux編程
之前,我對一個新的緩存封裝包寫單元測試的時候(該包擴展了Memcached API),我遇到了重寫Memcached::get()方法的問題。查看了 PHP文檔的Memcached::get()方法,有三個參數必須添加到我的擴展簽名,當我添加後,卻一直得到“… should be compatible with that of Memcached::get()”的錯誤提示。我嘗試著查找這個方法的簽名源代碼,但是從 PECL文檔中沒有找到任何有用的東西。於是,我使用PHP的 RelectionClass,看是否能找出哪裡丟失了擴展簽名從而引起了上述錯誤。幾分鐘後,我得出下面的代碼片斷:
1 $this->cache = Cache::factory(Cache::TYPE_VOLATILE); 2 3 $reflector = new ReflectionClass(get_class($this->cache)); 4 5 foreach ($reflector->getMethod('get')->getParameters() as $param) { 6 var_dump((string) $param); 7 }它輸出如下:
1 string(32) "Parameter #0 [ <required> $key ]" 2 string(37) "Parameter #1 [ <optional> $cache_cb ]" 3 string(39) "Parameter #2 [ <optional> &$cas_token ]"幾秒後,調查輸出結果,我發現我沒有通過引用傳遞第三個參數($cas_token),但是在我確定我的版本之前,我仔細檢查了PHP文檔的Memcached::get(),事實發現$cas_token確實被引用傳遞過去了(通過&符號)。然後,我修改了我的擴展方法,第三個參數通過引用傳遞,一切又如預期的那樣。

當你需要確定一個API的時候,卻沒有相關的文檔,可以嘗試使用PHP的ReflectorClass來得到相關信息。

Copyright © Linux教程網 All Rights Reserved