php反射api

官方文档: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);
                    }
                }


 

更多的例子可以在官方文档中看看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值