PHP反射

利用 PHP 的反射 API 可以很方便的得到指定对象所属的类结构,没有参考文档的时候可以很方便的探寻类的信息。另外还可以利用反射实现插件功能、生成代码文档。
这里写图片描述

OK!以上内容背完了,其实作为小白的我根本没用过。

先上传送门
但是,作为一个有探索精神的有志青年(diao si qing nian),尝试写了一小段利用反射描述类结构的代码!先记着,用的时候来翻翻…………..(一直不用会忘的,哎!已经忘了好多东西了!!!)

public function index() {
    header("Content-Type:text/html; charset=utf-8");
    //ThinkPHP 中实例化 model 对象的快捷函数
    $model = D('Company');
    $reflectO = new \ReflectionObject( $model );
    $reflection = new \Reflection();
    $properties = $reflectO->getProperties();
    $methods = $reflectO->getMethods();
    $className = $reflectO->getName();
    $line = str_repeat('-', 50) . PHP_EOL;
    $separator = str_repeat('*', 50) . PHP_EOL;
    $data = '';
    $data .= $separator . PHP_EOL  . $className . ' 类的成员属性信息' . PHP_EOL . PHP_EOL . $separator . PHP_EOL;
    //属性信息
    foreach ($properties as $p) {
        if( $p->isStatic() ){
            $data .= 'static   ';
        }
        $data .= $reflection->getModifierNames($p->getModifiers())[0] . '   ';
        $data .= $p->getName()  . PHP_EOL;
    }
    $data .= PHP_EOL . $separator . PHP_EOL  . $className . ' 类的成员方法信息' . PHP_EOL . PHP_EOL . $separator . PHP_EOL;
    //方法信息
    foreach ($methods as $m) {
        $params = $m->getParameters();
        $data .= $m->getDocComment() . PHP_EOL; //  方法的注释
        $data .= $reflection->getModifierNames($m->getModifiers())[0] . '   '; //  权限修饰符
        $data .=  $m->getName() . '( ';  //  方法名
        $var = array();
        foreach ($params as $param) {
            $index = $param->getPosition();
            if( !$param->isOptional()  ) { //无默认参数
                $var[$index] =  '$' . $name = $param->getName();
            } else {        //有默认参数
                $var[$index] =  '$' . $name = $param->getName() . '=' . $param->getDefaultValue();
                if( $param->getDefaultValue() == '') {
                    $var[$index] .=  '""';
                }
            }
        }
        $var = implode(", ", $var);
        $data .= $var . ' ){...}' . PHP_EOL;
        $data .= $line;     //  分割线
    }
    //写入、保存文件
    $fileName = basename($reflectO->getFileName());
    $filePath = '.' . DIRECTORY_SEPARATOR . $fileName;
    $fp = fopen($fileName, 'w');
    fwrite($fp, $data);
    fclose($fp);
    if( !file_exists($filePath) ) {
        echo '文件保存失败!';
    }
    echo '保存文件在:' , $filePath . '<br />文件大小:' . round(filesize($filePath)/1024, 2) . ' KB';
}

运行以上代码生成的文件如下:

**************************************************

Home\Model\CompanyModel 类的成员属性信息

**************************************************

protected   tablePrefix
..........省略.........

**************************************************

Home\Model\CompanyModel 类的成员方法信息

**************************************************


public   getCompanyName( $userCodes ){...}
--------------------------------------------------
/**
     * 架构函数
     * 取得DB类的实例对象 字段检查
     * @access public
     * @param string $name 模型名称
     * @param string $tablePrefix 表前缀
     * @param mixed $connection 数据库连接信息
     */
public   __construct( $name="", $tablePrefix="", $connection="" ){...}
--------------------------------------------------
/**
     * 自动检测数据表信息
     * @access protected
     * @return void
     */
protected   _checkTableInfo(  ){...}
--------------------------------------------------

..................省略................

其实如果想看对象的成员属性直接打印会更详尽,比如:

$model = D('company');
var_dump( $model );

得到以下内容(是不是很尴尬,但对象内部只是数据,类的方法只能通过反射来获得)。

object(Home\Model\CompanyModel)[6]
  protected 'tablePrefix' => string '' (length=0)
  protected 'tableName' => string 'company' (length=7)
  protected 'fields' => 
    array (size=19)
      0 => string 'region_name' (length=11)
      1 => string 'region_code' (length=11)
      2 => string 'parent_name' (length=11)
      3 => string 'parent_code' (length=11)
      4 => string 'longitude' (length=9)
      5 => string 'latitude' (length=8)
      6 => string 'isvalid' (length=7)
      7 => string 'holder_name' (length=11)
      8 => string 'holder_code' (length=11)
      9 => string 'create_date' (length=11)
      10 => string 'company_scope' (length=13)
      11 => string 'company_phone' (length=13)
      12 => string 'company_name' (length=12)
      13 => string 'company_logourl' (length=15)
      14 => string 'company_linker' (length=14)
      15 => string 'company_desc' (length=12)
      16 => string 'company_code' (length=12)
      17 => string 'company_addr' (length=12)
      18 => string 'biz_citys' (length=9)
  protected 'pk' => string 'company_code' (length=12)
  protected 'db' => 
    object(Think\Db\Driver\Mysql)[7]
      protected 'PDOStatement' => null
      protected 'model' => string '_think_' (length=7)
      protected 'queryStr' => string '' (length=0)
      protected 'modelSql' => 
              array (size=0)
          empty
          ............略.........
posted @ 2015-10-15 17:44  PeterZhaoChina  阅读(150)  评论(0编辑  收藏  举报