官方文档:http://www.php.net/manual/en/book.reflection.php
反射简单的理解就是根据实例化的对象查看类的信息,通过对象反射类
<?php
class test
{
public function index()
{
return "dd";
}
}
$test = new test();
$class = new ReflectionClass($test);
$result = $class->getMethod('index')->invoke($test);
var_dump($result);
上面就是通过反射来执行test的index方法,效果与实例化一个类,然后通过对象访问方法一样,这样做等于多了一步检查方法是否存在,不存在会抛出一个异常,可以加上try catch测试下。
反射常应用与插件式架构的项目中,我们不知道类的任何信息,程序提前定义好接口,开发者实现这个接口的方法;在一些框架中也是用这种方式的,如thinkphp:
<?php
//Lib/Core/App.class.php
//执行当前操作
$method = new ReflectionMethod($module, $action);
if($method->isPublic()) {
$class = new ReflectionClass($module);
// 前置操作
if($class->hasMethod('_before_'.$action)) {
$before = $class->getMethod('_before_'.$action);
if($before->isPublic()) {
$before->invoke($module);
}
}
/**/
// 前置操作(所有的方法前均会调用)@自加
if($class->hasMethod('preMethod')) {
$pre = $class->getMethod('preMethod');
if($pre->isPublic()) {
$pre->invoke($module);
}
}
更多的例子可以在官方文档中看看