反射机制与动态代理

反射机制可以通过PHP代码得到某类/方法等的所有信息,并且可以和它交互。

反射类可得到的信息

ReflectionFunction() 函数定义所在的文件及起始位置

ReflectionClass() 常量/属性/方法/命名空间/类是否为final或abstract等

ReflectionMethod() 方法修饰类型/方法名/方法注释等

反射机制的应用:

动态代理:也叫委托模式。在委托模式中,有两个对象参与处理同一个请求,接受请求的对象将请求委托给另一个对象来处理。

插件系统:利用反射机制自动获取插件列表以及其他的相关信息。


函数的反射机制的应用

<?php

  function Test(){ echo 'i'm test .';}

  Test();

  $ref_fun = new ReflectionFunction('Test');

  echo $ref_fun->getDocComment().'<br/>';//获取函数注释

  echo $ref_fun->getFileNmae().'<br/>';//函数定义所在的文件

  echo $ref_fun->getStartLine().'<br/>';//开始行

  echo $ref_fun->getEndLine().'<br/>';//结束行

  try

 

     new ReflectionFunction('Test1'); 

  }catch(ReflectionException,$e){ 

        echo $e->getMessage(); } 

  throw

  {  

        $e;

  }

?>


类的反射机制的应用

<?php

  class A{

  function t1()

  {

      echo '我没有参数';

  }

  function t2($aa)

  {

      echo '我带了一个参数';

  }

  function t3()

  {

  }

  static function t4()

  {

      echo '我是静态的';

  }

}


$a = new A();

$ref_cls = new ReflectionClass('A');//参数可以是类名也可以是类的一个实例 Reflection($a)


//获取所有方法

$class_all_method = $ref_cls->getMethods();

print_r($class_all_method);

echo '<br/>';


//判断类中是否有某个方法

var_dump($ref_cls->hasMethod('t8'));


//判断方法的修饰符

//判断方式:is+修饰符 返回boolean

//判断之前要获取类的方法


第一种方法

ref_method = $ref_cls->getMethod('t3');

var_dump($ref_method->isPublic());//是否公开方法 

第二种方法

$ref_method = new ReflectionMethod('A','t4');

var_dump($ref_method->isStatic());//是否静态方法


//执行方法

//静态公开方法调用 invoke(null,参数);

//普通方法调用 invoke(实力对象,参数);

if($ref_method->isStatic && $ref_method->isPublic && $ref_method->isAbstract()){

$ref_method->invoke(null);}else{

$ref_method->invoke($a);}

?>


反射机制与动态代理