這篇文章主要介紹了PHP的反射類ReflectionClass、ReflectionMethod使用實例,本文同時介紹了反射是什麼、反射可以做哪些事情,並給出一個具體例子,是一篇不錯的入門文章,需要的朋友可以參考下
PHP5 具有完整的反射API,增加對類別、介面、函數、方法和擴充進行反向工程的能力。
反射是什麼?
它是指在PHP運行狀態中,擴展分析PHP程序,導出或提取關於類別、方法、屬性、參數等的詳細信息,包括註釋。這種動態所獲取的資訊以及動態呼叫物件的方法的功能稱為反射API。反射是操縱物件導向範式中元模型的API,其功能十分強大,可幫助我們建立複雜,可擴展的應用。
其用途如:自動載入插件,自動產生文檔,甚至可用來擴充PHP語言。
PHP反射api由若干類別組成,可幫助我們用來存取程式的元資料或同相關的註解互動。借助反射我們可以取得諸如類別實作了那些方法,創建一個類別的實例(不同於用new創建),呼叫一個方法(也不同於常規呼叫),傳遞參數,動態呼叫類別的靜態方法。
反射api是PHP內建的OOP技術擴展,包括一些類,異常和接口,綜合使用他們可用來幫助我們分析其它類,接口,方法,屬性,方法和擴展。這些OOP擴展稱為反射。
平常我們用的比較多的是ReflectionClass類別和ReflectionMethod類,例如:
程式碼如下:
<?php class Person { /** * For the sake of demonstration, we"re setting this private */ private $_allowDynamicAttributes = false; /** * type=primary_autoincrement */ protected $id = 0; /** * type=varchar length=255 null */ protected $name; /** * type=text null */ protected $biography; public function getId() { return $this->id; } public function setId($v) { $this->id = $v; } public function getName() { return $this->name; } public function setName($v) { $this->name = $v; } public function getBiography() { return $this->biography; } public function setBiography($v) { $this->biography = $v; } }
一、透過ReflectionClass,我們可以得到Person類別的以下資訊:
1.常數Contants
2.屬性Property Names
3.方法Method Names靜態
4.屬性Static Properties
5 .命名空間 Namespace
6.Person類別是否為final或abstract
7.Person類別是否有某個方法
接下來反射它,只要把類別名稱" Person"傳遞給ReflectionClass就可以了:
程式碼如下:
$class = new ReflectionClass('Person'); // 建立 Person这个类的反射类 $instance = $class->newInstanceArgs($args); // 相当于实例化Person 类
1)取得屬性(Properties):
程式碼如下:
$properties = $class->getProperties(); foreach($properties as $property) { echo $property->getName() . "\n"; } // 输出: // _allowDynamicAttributes // id // name // biography
預設情況下,ReflectionClass會取得到所有的屬性,private 和protected的也可以。如果只想取得到private屬性,就要額外傳個參數:
#程式碼如下:
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
可用參數清單:
程式碼如下:
ReflectionProperty::IS_STATIC ReflectionProperty::IS_PUBLIC ReflectionProperty::IS_PROTECTED ReflectionProperty::IS_PRIVATE
透過$property->getName()可以得到屬性名稱。
2)取得註解:
透過getDocComment可以得到寫給property的註解。
程式碼如下:
foreach ($properties as $property) { if ($property->isProtected()) { $docblock = $property->getDocComment(); preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches); echo $matches[1] . "\n"; } } // Output: // primary_autoincrement // varchar // text
3)取得類別的方法
程式碼如下:
getMethods() 来获取到类的所有methods。 hasMethod(string) 是否存在某个方法 getMethod(string) 获取方法
4)執行類別的方法:
# 程式碼如下:
$instance->getName(); // 执行Person 里的方法getName // 或者: $method = $class->getmethod('getName'); // 获取Person 类中的get Name方法 $method->invoke($instance); // 执行getName 方法 // 或者: $method = $class->getmethod('setName'); // 获取Person 类中的setName方法 $method->invokeArgs($instance, array('snsgou.com'));
二、透過ReflectionMethod,我們可以得到Person類別的某個方法的資訊:
1.是否「public」、「protected」、「private」、「static」類型
2.方法的參數列表
3.方法的參數數量
4.反呼叫類別的方法
#程式碼如下:
// 执行detail方法 $method = new ReflectionMethod('Person', 'test'); if ($method->isPublic() && !$method->isStatic()) { echo 'Action is right'; } echo $method->getNumberOfParameters(); // 参数个数 echo $method->getParameters(); // 参数对象数组
以上是php中2種反射類別ReflectionClass、ReflectionMethod用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你應該關心DependencyInjection(DI),因為它能讓你的代碼更清晰、更易維護。 1)DI通過解耦類,使其更模塊化,2)提高了測試的便捷性和代碼的靈活性,3)使用DI容器可以管理複雜的依賴關係,但要注意性能影響和循環依賴問題,4)最佳實踐是依賴於抽象接口,實現鬆散耦合。

是的,優化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)優化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,並避免使用

theKeyStrategiestosigantificallyBoostPhpaPplicationPerformenCeare:1)UseOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)優化AtabaseInteractionswithPreparedStateTementStatementStatementAndProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增強codemodocultion,可驗證性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

選擇DependencyInjection(DI)用於大型應用,ServiceLocator適合小型項目或原型。 1)DI通過構造函數注入依賴,提高代碼的測試性和模塊化。 2)ServiceLocator通過中心註冊獲取服務,方便但可能導致代碼耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)啟用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替換loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化進行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。