PHP的反射动态获取类方法、属性、参数操作示例

来自:互联网
时间:2020-03-07
阅读:

本文实例讲述了PHP的反射动态获取类方法、属性、参数操作。分享给大家供大家参考,具体如下:

我们可以在PHP运行时,通过PHP的反射动态的获取类的方法、属性、参数等详细信息。

用途:插件的设计,文档的自动生成,扩充PHP语言。

<?php
class Person {
  const weightUnit = 'kg';
  const heightUnit = 'cm';
  public $name = 'test';
  public $age = 1;
  public function say($msg = '') {
    echo $msg;
  }
}

$p = new Person ();
// 普通的实例化对象,调用方法
$p->say ( 'hello' );
echo "<br/>";
// 创建一个Person的反射类
$rp = new ReflectionClass ( 'Person' );

// 通过ReflectionClass的方法来获取类的详细信息

// 获取常量
echo $rp->getConstant ( 'weightUnit' );
echo "<br/>";
// 获取类中已定义的常量
var_dump ( $rp->getConstants () );

// 获取属性,返回的是一个ReflectionProperty类
$propName = $rp->getProperty ( 'name' );
echo $propName->getName(), ':', $propName->getValue ( new Person () );
echo "<br/>";
// 获取类中已定义的一组属性
$propArr = $rp->getProperties ();
foreach ( $propArr as $obj ) {
  echo $obj->getName (), ':', $obj->getValue ( new Person () );
}
echo "<br/>";
//获取方法,返回的是一个ReflectionMethod类
$sayMetd = $rp->getMethod('say');
if($sayMetd->isPublic() && !$sayMetd->isAbstract()) {
  $sayMetd->invoke(new Person(), 'hehe');
  $sayMetd->invokeArgs(new Person(), array('hehe'));
}

//获取类中已定义的一组方法,可以过滤不需要的方法
$metds = $rp->getMethods();

//获取命名空间
echo $rp->getNamespaceName();
echo "<br/>";
//判断一个方法是否定义
if($rp->hasMethod('say')) {
  echo 'say has';
}
echo "<br/>";
//判断一个属性是否定义
if($rp->hasProperty('name')) {
  echo 'name has';
}

运行结果:

hello
kg
array(2) { ["weightUnit"]=> string(2) "kg" ["heightUnit"]=> string(2) "cm" } name:test
name:testage:1
hehehehe
say has
name has

返回顶部
顶部