今天无意间看之前使用过的一个框架,想到这个框架可以根据controller的action中的注释来决定执行该动作是否需要进行身份验证,就想研究一下他是怎么实现的。找到了相应的实现位置,发现里面使用了大量的反射特性。刚好我对反射也不熟,所以就像研究研究。
首先了解到了一个函数:get_declared_classes()
,这个函数可以返回当前载入的所有类的类名组成的数组。于是我运行一下,看看php中内置的有哪几个反射类。内置的反射类如下,我们可以根据反射来分析这几个类的提供了哪些方法和属性,其实很多的IDE实现的代码自动提示使用的就是这个特性,我们也可以使用这种方法来研究下面的这些类例如下面的第一个反射异常类 : Reflection::export(new ReflectionClass('ReflectionException'));
ReflectionException
反射异常类,这个和普通的异常类基本功能一样,没有什么好说的
Reflection
反射基础类,这个类只提供了两个静态方法:
- Static methods [2] {
Method [ <internal:Reflection> static public method getModifierNames ] { // 这个方法我还不知道是做什么用的
- Parameters [1] {
Parameter #0 [ <required> $modifiers ]
}
}
Method [ <internal:Reflection> static public method export ] { // 这个方法递归的现实传递进来的reflector
- Parameters [2] {
Parameter #0 [ <required> Reflector $reflector ] // 必要参数,实现Reflector接口的对象
Parameter #1 [ <optional> $return ]
}
}
}
ReflectionFunctionAbstract
函数反射的抽象类,这个类实现的方法比较多,这里就不再贴出“export”的代码,他主要实现的方法有:
getDocComment:获取函数的块注释
inNamespace: 获取所属命名空间
isClosure:是否闭包
getParameters:获取函数的参数
getNumberOfRequiredParameters:获取函数的必要参数的数量
getNumberOfParameters:获取函数所有参数的数量
getStaticVariables:获取函数的静态变量
ReflectionFunction
ReflectionParameter
ReflectionMethod
ReflectionClass
ReflectionObject
ReflectionProperty
ReflectionExtension
这个类将展示某个扩展的所有相关信息,