1.5反射--php反射学习

1.5反射--php反射学习

http://blog.csdn.net/rforce/article/details/75330306

原创 2017年07月18日 20:29:35

反射-Reflection

PHP 5 具有完整的反射 API,添加了对类、接口、函数、方法和扩展进行反向工程的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。

 

 

1.反射有什么作用

  • 反射可以用作文档生成。
  • 反射可以做hook插件功能或者动态代理

通过反射我们可以得到一个类的相关属性:

  • 常量 Contants
  • 属性 Property Names
  • 方法 Method Names静态
  • 属性 Static Properties
  • 命名空间 Namespace
  • 类是否为final或者abstract

2.如何使用反射

2.1获得反射

如下有一个简单的Person类

<?php

class Person {
    protected $name ;
    protected $age;

    public function getName() {  
            return $this->name;  
    }

    public static function getAge() {
        return $this->age;
    }  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

我们只需要把类名’Person’传给ReflectionClass即可得到Person的反射。

$class = new ReflectionClass('Person');
$instance  = $class->newInstanceArgs();
  • 1
  • 2

2.2获取属性

$properties = $class->getProperties();
foreach( $properties as $pro ) {
    echo $pro->getName()."\n";
}
  • 1
  • 2
  • 3
  • 4

输出如下:

2.3获取方法

$method = $class->getMethods();
var_dump($method);
  • 1
  • 2

输出如下:

2.4执行类的方法

$getName = $method[0];
$getName->invoke($instance);
//或者
$instance->getName();
  • 1
  • 2
  • 3
  • 4

上述就可以执行类中的方法。

 
posted @ 2018-01-31 17:17  sky20080101  阅读(51)  评论(0)    收藏  举报