最近在看java编程思想,看到类型信息这一章,讲到了类的信息以及反射的概念。顺便温故一下php的反射东西。手册是这样说的:"PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。"当然手册上说的有些抽象!所谓的逆向说白就是能获取关于类、方法、属性、参数等的详细信息,包括注释! 文字总是那么枯燥,举个例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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 这个类返回时某个类的相关的信息,比如 属性,方法,命名空间,实现那些接口等!上个例子中ReflectionClass:: getProperties 返回是 ReflectionProperty 对象的数组。
ReflectionProperty 类报告了类的属性的相关信息。比如 isDefault isPrivate isProtected isPublic isStatic等,方法getName 是获取属性的名称!
以上是获取属性的,还有获取类方法的比如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 类报告了一个方法的有关信息,比如 isAbstract isPrivate isProtected isPublic isStatic isConstructor,还有一个重要的方法Invoke,InvokeArgs 就是执行方法!
其他的对象可以看看手册,不是很难!
那反射究竟有哪些用途?
反射是一个动态运行的概念,综合使用他们可用来帮助我们分析其它类,接口,方法,属性,方法和扩展。还可构建模式,比如动态代理。在一些php框架中使用反射也是很经常,比如kohana,yii,下面是kohana 的实现mvc的代码,就是用到了反射!
1
2
3
4
5
6
7
8
|
// 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可以获取哪个控制器、哪个方法!然后再执行方法!
以上就是对PHP 反射的资料整理,后续继续补充相关资料,谢谢大家对本站的支持!