搜尋
首頁後端開發php教程PHP反射使用实例和PHP反射API的中文说明_PHP

最近在开发过程中需要获取某个类方法的参数数量、名称及参数顺序,好根据参数的名称来从$_GET里取值。

如方法原型为test($uid,$score), 那么我就知道需要需要从$_GET取
复制代码 代码如下:
$uid = $_GET['uid'];

$score = $_GET['score'];

然后调用方法$obj->test($uid,$score)

当然前提是约定好了参数名称和get方法传值变量名一致。

采用PHP的反射API,获得函数参数名称和参数默认值的方法如下:
复制代码 代码如下:
class testClass{ 
     
    public function testFunc($param1,$param2=0){ 
         
    } 

 
$method = new ReflectionMethod('testClass', 'testFunc'); 
$params = $method--->getParameters(); 
foreach ($params as $param) { 
    echo 'param name: ' . $param->getName(),"\n"; 
    if ($param->isOptional()) { 
        echo 'Default value: ' . $param->getDefaultValue(),"\n"; 
    } 

下面是PHP反射API的介绍:

1、用途:
该扩展分析php程序,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。
Reflection可以说是对php库函数:“Classes/Objects 类/对象函数”的一个扩展。
主要用在通过程序检测现有php程序内部关于类、方法等信息,并做出处理。

2、API概览:
复制代码 代码如下:
class Reflection { } 
interface Reflector { } 
class ReflectionException extends Exception { } 
class ReflectionFunction implements Reflector { } 
class ReflectionParameter implements Reflector { } 
class ReflectionMethod extends ReflectionFunction { } 
class ReflectionClass implements Reflector { } 
class ReflectionObject extends ReflectionClass { } 
class ReflectionProperty implements Reflector { } 
class ReflectionExtension implements Reflector { } 

3、详细说明:(例子详见php手册)
复制代码 代码如下:
①Reflection类 
class Reflection 

public static mixed export(Reflector r [,bool return]) 
//导出一个类或方法的详细信息 
public static array getModifierNames(int modifiers) 
//取得修饰符的名字 

?> 
 
②ReflectionException类 
 
该类继承标准类,没特殊方法和属性。 
 
③ReflectionFunction类 
class ReflectionFunction implements Reflector 

final private __clone() 
public object __construct(string name) 
public string __toString() 
public static string export() 
//导出该函数的详细信息 
public string getName() 
//取得函数名 
public bool isInternal() 
//测试是否为系统内部函数 
public bool isUserDefined() 
//测试是否为用户自定义函数 
public string getFileName() 
//取得文件名,包括路径名 
public int getStartLine() 
//取得定义函数的起始行 
public int getEndLine() 
//取得定义函数的结束行 
public string getDocComment() 
//取得函数的注释 
public array getStaticVariables() 
//取得静态变量 
public mixed invoke(mixed* args) 
//调用该函数,通过参数列表传参数 
public mixed invokeArgs(array args) 
//调用该函数,通过数组传参数 
public bool returnsReference() 
//测试该函数是否返回引用 
public ReflectionParameter[] getParameters() 
//取得该方法所需的参数,返回值为对象数组 
public int getNumberOfParameters() 
//取得该方法所需的参数个数 
public int getNumberOfRequiredParameters() 
//取得该方法所需的参数个数 

?> 
 
④ReflectionParameter类: 
class ReflectionParameter implements Reflector 

final private __clone() 
public object __construct(string name) 
public string __toString() 
public static string export() 
//导出该参数的详细信息 
public string getName() 
//取得参数名 
public bool isPassedByReference() 
//测试该参数是否通过引用传递参数 
public ReflectionClass getClass() 
//若该参数为对象,返回该对象的类名 
public bool isArray() 
//测试该参数是否为数组类型 
public bool allowsNull() 
//测试该参数是否允许为空 
public bool isOptional() 
//测试该参数是否为可选的,当有默认参数时可选 
public bool isDefaultValueAvailable() 
//测试该参数是否为默认参数 
public mixed getDefaultValue() 
//取得该参数的默认值 

?> 
 
⑤ReflectionClass类: 
class ReflectionClass implements Reflector 

final private __clone() 
public object __construct(string name) 
public string __toString() 
public static string export() 
//导出该类的详细信息 
public string getName() 
//取得类名或接口名 
public bool isInternal() 
//测试该类是否为系统内部类 
public bool isUserDefined() 
//测试该类是否为用户自定义类 
public bool isInstantiable() 
//测试该类是否被实例化过 
public bool hasConstant(string name) 
//测试该类是否有特定的常量 
public bool hasMethod(string name) 
//测试该类是否有特定的方法 
public bool hasProperty(string name) 
//测试该类是否有特定的属性 
public string getFileName() 
//取得定义该类的文件名,包括路径名 
public int getStartLine() 
//取得定义该类的开始行 
public int getEndLine() 
//取得定义该类的结束行 
public string getDocComment() 
//取得该类的注释 
public ReflectionMethod getConstructor() 
//取得该类的构造函数信息 
public ReflectionMethod getMethod(string name) 
//取得该类的某个特定的方法信息 
public ReflectionMethod[] getMethods() 
//取得该类的所有的方法信息 
public ReflectionProperty getProperty(string name) 
//取得某个特定的属性信息 
public ReflectionProperty[] getProperties() 
//取得该类的所有属性信息 
public array getConstants() 
//取得该类所有常量信息 
public mixed getConstant(string name) 
//取得该类特定常量信息 
public ReflectionClass[] getInterfaces() 
//取得接口类信息 
public bool isInterface() 
//测试该类是否为接口 
public bool isAbstract() 
//测试该类是否为抽象类 
public bool isFinal() 
//测试该类是否声明为final 
public int getModifiers() 
//取得该类的修饰符,返回值类型可能是个资源类型 
//通过Reflection::getModifierNames($class->getModifiers())进一步读取 
public bool isInstance(stdclass object) 
//测试传入的对象是否为该类的一个实例 
public stdclass newInstance(mixed* args) 
//创建该类实例 
public ReflectionClass getParentClass() 
//取得父类 
public bool isSubclassOf(ReflectionClass class) 
//测试传入的类是否为该类的父类 
public array getStaticProperties() 
//取得该类的所有静态属性 
public mixed getStaticPropertyValue(string name [, mixed default]) 
//取得该类的静态属性值,若private,则不可访问 
public void setStaticPropertyValue(string name, mixed value) 
//设置该类的静态属性值,若private,则不可访问,有悖封装原则 
public array getDefaultProperties() 
//取得该类的属性信息,不含静态属性 
public bool isIterateable() 
public bool implementsInterface(string name) 
//测试是否实现了某个特定接口 
public ReflectionExtension getExtension() 
public string getExtensionName() 

?> 
 
⑥ReflectionMethod类: 
class ReflectionMethod extends ReflectionFunction 

public __construct(mixed class, string name) 
public string __toString() 
public static string export() 
//导出该方法的信息 
public mixed invoke(stdclass object, mixed* args) 
//调用该方法 
public mixed invokeArgs(stdclass object, array args) 
//调用该方法,传多参数 
public bool isFinal() 
//测试该方法是否为final 
public bool isAbstract() 
//测试该方法是否为abstract 
public bool isPublic() 
//测试该方法是否为public 
public bool isPrivate() 
//测试该方法是否为private 
public bool isProtected() 
//测试该方法是否为protected 
public bool isStatic() 
//测试该方法是否为static 
public bool isConstructor() 
//测试该方法是否为构造函数 
public bool isDestructor() 
//测试该方法是否为析构函数 
public int getModifiers() 
//取得该方法的修饰符 
public ReflectionClass getDeclaringClass() 
//取得该方法所属的类 
// Inherited from ReflectionFunction 
final private __clone() 
public string getName() 
public bool isInternal() 
public bool isUserDefined() 
public string getFileName() 
public int getStartLine() 
public int getEndLine() 
public string getDocComment() 
public array getStaticVariables() 
public bool returnsReference() 
public ReflectionParameter[] getParameters() 
public int getNumberOfParameters() 
public int getNumberOfRequiredParameters() 

?> 
 
⑦ReflectionProperty类: 
class ReflectionProperty implements Reflector 

final private __clone() 
public __construct(mixed class, string name) 
public string __toString() 
public static string export() 
//导出该属性的详细信息 
public string getName() 
//取得该属性名 
public bool isPublic() 
//测试该属性名是否为public 
public bool isPrivate() 
//测试该属性名是否为private 
public bool isProtected() 
//测试该属性名是否为protected 
public bool isStatic() 
//测试该属性名是否为static 
public bool isDefault() 
public int getModifiers() 
//取得修饰符 
public mixed getValue(stdclass object) 
//取得该属性值 
public void setValue(stdclass object, mixed value) 
//设置该属性值 
public ReflectionClass getDeclaringClass() 
//取得定义该属性的类 
public string getDocComment() 
//取得该属性的注释 

?> 
 
⑧ReflectionExtension类 
class ReflectionExtension implements Reflector { 
final private __clone() 
public __construct(string name) 
public string __toString() 
 
public static string export() 
//导出该扩展的所有信息 
public string getName() 
//取得该扩展的名字 
public string getVersion() 
//取得该扩展的版本 
public ReflectionFunction[] getFunctions() 
//取得该扩展的所有函数 
public array getConstants() 
//取得该扩展的所有常量 
public array getINIEntries() 
//取得与该扩展相关的,在php.ini中的指令信息 
public ReflectionClass[] getClasses() 
public array getClassNames() 

?> 

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱門文章

熱工具

Safe Exam Browser

Safe Exam Browser

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

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具