php 的反射詳解及示例代碼
最近在看java編程思想,看到類型信息這一章,講到了類的信息以及反射的概念。順便溫故一下php的反射東西。手冊是這樣說的:"PHP 5 具有完整的反射 API,添加了對類、接口、函數(shù)、方法和擴展進行反向工程的能力。 此外,反射 API 提供了方法來取出函數(shù)、類和方法中的文檔注釋。"當(dāng)然手冊上說的有些抽象!所謂的逆向說白就是能獲取關(guān)于類、方法、屬性、參數(shù)等的詳細(xì)信息,包括注釋! 文字總是那么枯燥,舉個例子
class Foo { public $foo = 1; protected $bar = 2; private $baz = 3; /** * Enter description here ... */ public function myMethod() { echo 'hello 2b'; } } $ref = new ReflectionClass('Foo'); $props = $ref->getProperties(); foreach ($props as $value) { echo $value->getName()."\n"; } //output //foo //bar //baz
ReflectionClass 這個類返回時某個類的相關(guān)的信息,比如 屬性,方法,命名空間,實現(xiàn)那些接口等!上個例子中ReflectionClass:: getProperties 返回是 ReflectionProperty 對象的數(shù)組。
ReflectionProperty 類報告了類的屬性的相關(guān)信息。比如 isDefault isPrivate isProtected isPublic isStatic等,方法getName 是獲取屬性的名稱!
以上是獲取屬性的,還有獲取類方法的比如
class Foo { public $foo = 1; protected $bar = 2; private $baz = 3; /** * Enter description here ... */ public function myMethod() { echo 'hello 2b'; } } $ref = new ReflectionClass('Foo'); $method = $ref->getMethod('myMethod'); $method->invoke($ref->newInstance());
ReflectionClass::getMethod 是反是一個 ReflectionMethod 類型 ,ReflectionMethod 類報告了一個方法的有關(guān)信息,比如 isAbstract isPrivate isProtected isPublic isStatic isConstructor,還有一個重要的方法Invoke,InvokeArgs 就是執(zhí)行方法!
其他的對象可以看看手冊,不是很難!
那反射究竟有哪些用途?
反射是一個動態(tài)運行的概念,綜合使用他們可用來幫助我們分析其它類,接口,方法,屬性,方法和擴展。還可構(gòu)建模式,比如動態(tài)代理。在一些php框架中使用反射也是很經(jīng)常,比如kohana,yii,下面是kohana 的實現(xiàn)mvc的代碼,就是用到了反射!
// Start validation of the controller $class = new ReflectionClass(ucfirst(Router::$controller).'_Controller'); // Create a new controller instance $controller = $class->newInstance(); // Load the controller method $method = $class->getMethod(Router::$method); // Execute the controller method $method->invokeArgs($controller, $arguments);
上面的代碼可以清晰看到這個框架的流程!通過Router 其實就處理url的類,通過Router可以獲取哪個控制器、哪個方法!然后再執(zhí)行方法!
以上就是對PHP 反射的資料整理,后續(xù)繼續(xù)補充相關(guān)資料,謝謝大家對本站的支持!
相關(guān)文章
laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作實例分析
這篇文章主要介紹了laravel框架數(shù)據(jù)庫操作、查詢構(gòu)建器、Eloquent ORM操作,結(jié)合實例形式分析了laravel數(shù)據(jù)庫連接、增刪改查、排序及Eloquent ORM數(shù)據(jù)庫操作等相關(guān)使用技巧,需要的朋友可以參考下2019-12-12php中使用array_filter()函數(shù)過濾空數(shù)組的實現(xiàn)代碼
這篇文章主要介紹了php中使用array_filter()函數(shù)過濾空數(shù)組的實現(xiàn)代碼,這是瀏覽PHP手冊時無意發(fā)意的一個有意思的array_filter()函數(shù)用法,需要的朋友可以參考下2014-08-08Laravel 5框架學(xué)習(xí)之日期,Mutator 和 Scope
這篇文章主要介紹了Laravel 5框架學(xué)習(xí)之日期,Mutator 和 Scope的相關(guān)資料,需要的朋友可以參考下2015-04-04php安裝xdebug/php安裝pear/phpunit詳解步驟(圖)
PHP環(huán)境中安裝pear、phpunit以及xdebug全攻略,大家參考使用吧2013-12-12如何使用PHP file_exists函數(shù)檢查文件是否存在
這篇文章主要為大家介紹了PHP函數(shù)file_exists檢查文件是否存在實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01Laravel框架實現(xiàn)的使用smtp發(fā)送郵件功能示例
這篇文章主要介紹了Laravel框架實現(xiàn)的使用smtp發(fā)送郵件功能,結(jié)合實例形式分析了Laravel框架相關(guān)配置及郵件發(fā)送操作技巧,需要的朋友可以參考下2019-03-03