工厂模式-PHP的反射机制

通过PHP代码,就可以得到某object的所有信息,并且可以和它交互反射api是php内建的oop技术扩展,包括一些类,异常和接口,综合使用他们可用来帮助我们分析其它类,接口,方法,属性,方法和扩展。这些oop扩展被称为反射。
通过ReflectionClass,我们可以得到Person类的以下信息:

  1. 常量Contants
  2. 属性 Property Names
  3. 方法 Method Names静态
  4. 属性 Static Properties
  5. 命名空间 Namespace
  6. Person类是否为final或者abstract
<?php
class Person
{
    /**
     * For the sake of demonstration, we"re setting this private
     */
    private $_allowDynamicAttributes = false;

    /** type=primary_autoincrement */
    protected $id = 0;

    /** type=varchar length=255 null */
    protected $name;

    /** type=text null */
    protected $biography;

    public function getId()
    {
        return $this->id;
    }

    public function setId($v)
    {
        $this->id = $v;
    }

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

    public function setName($v)
    {
        $this->name = $v;
    }

    public function getBiography()
    {
        return $this->biography;
    }

    public function setBiography($v)
    {
        $this->biography = $v;
    }
}

 接下来反射它,只要把类名"Person"传递给ReflectionClass就可以了:

<?php
$class = new ReflectionClass('Person'); //建立Person这个类的反射类
$instance = $class->newInstanceArgs();//相当于实例化Person类

1)获取属性(Properties)

<?php
$properties = $class->getProperties();
foreach ($properties as $property) {
    echo $property->getName() . "\n";
}
// 输出:
// _allowDynamicAttributes
// id
// name
// biography

默认情况下,ReflectionClass会获取到所有的属性,private 和 protected的也可以。如果只想获取到private属性,就要额外传个参数:

$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);

可用参数列表:

  • ReflectionProperty::IS_STATIC
  • ReflectionProperty::IS_PUBLIC
  • ReflectionProperty::IS_PROTECTED
  • ReflectionProperty::IS_PRIVATE

如果要同时获取public 和protected属性,就这样写:ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED。

2)获取注释

 通过getDocComment可以得到写给property的注释。

<?php
foreach ($properties as $property) {
    if ($property->isProtected()) {
        $docblock = $property->getDocComment();
        preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches);
        echo $matches[1] . "\n";
    }
}
// Output:
// primary_autoincrement
// varchar
// text

3)获取类的方法

获取方法(methods):通过getMethods() 来获取到类的所有methods。

4)执行类的方法:

<?php
$instance->getName(); //执行Person里的方法getName
//或者:
$ec = $class->getmethod('getName'); //获取Person 类中的getName方法
$ec->invoke($instance); //执行getName 方法

 555

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值