php 反射机制

反射:直观理解就是根据到达地找到出发地和来源。比如,一个光秃秃的对象,我们可以仅仅通过这个对象就能知道它所属的类、拥有哪些方法。

手册: 官网介绍

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

请注意部分内部 API 丢失了反射扩展工作所需的代码。 例如,一个内置的 PHP 类可能丢失了反射属性的数据。这些少数的情况被认为是错误,不过, 正因为如此,它们应该被发现和修复。

demo:通过ReflectionClass 类 ->反射 tets 类 ,得到中的属性和方法等

<?php
/**
 * test测试类
 */
class test
{
    /**
     * $test 属性
     */
    private $test = "";
	public  static $color='Red';
    public function setTest($test)
    {
        $this->test = $test;
        return $this;
    }
    /**
     * getTest 方法
     */
    public function getTest()
    {
        return $this->test;
    }
   
}

反射类

$class = new ReflectionClass(new test()); ## 反射test 类
    class ReflectionClass#1 (1) {
      public $name =>
      string(4) "test"
    }

获取类的方法名

$methods  =  $class -> getMethods ();     ## 获取方法的数组 
    array(2) {
      [0] =>
      class ReflectionMethod#2 (2) {
        public $name =>
        string(7) "setTest"
        public $class =>
        string(4) "test"
      }
      [1] =>
      class ReflectionMethod#3 (2) {
        public $name =>
        string(7) "getTest"
        public $class =>
        string(4) "test"
      }
    }

注释

$doc=$class->getDocComment();  // 获取test类的注释文档,即定义在类之前的注释
string(26) "/**
 * test测试类
 */"
$methoddoc = $class->getMethod('getTest')->getDocComment();  // 获取tets类中setPassowrd方法的注释
string(35) "/**
     * getTest 方法
     */"

获取静态(static)属性 及属于值

$static=$class->getStaticProperties();  获取静态(static)属性 
array (size=1)
  'color' => string 'Red' (length=3)
$vaule=$class->getStaticPropertyValue('color'); 获取静态(static)属性的值 
string 'Red' (length=3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值