bramus/reflection

更好的PHP反射库

资助包维护!
bramus

1.0 2019-05-13 06:47 UTC

This package is auto-updated.

Last update: 2024-09-08 04:31:43 UTC


README

Build Status Source Version Downloads License

bramus/reflection 是一个库,旨在使 PHP 的内置反射更好。

由 Bramus Van Damme (https://www.bram.us)贡献者 构建

先决条件/需求

  • PHP 7.2 或更高版本

安装

可以使用 Composer 进行安装

$ composer require bramus/reflection ~1.0

用法

注意

bramus/reflection 中的所有类都扩展了 PHP 的内置版本。因此,它们具有与父类相同的所有功能

ReflectionClass

\ReflectionClass 相比,\Bramus\Reflection\ReflectionClass 工作方式完全相同,但它将在调用 getConstants()

  • 返回一个包含 \Bramus\Reflection\ReflectionClassConstant 实例的关联数组 (而不是简单值)
  • 在调用 getConstant() 时返回一个 \Bramus\Reflection\ReflectionClassConstant 实例 (而不是简单值)

以下是一个比较 getConstant() 的示例;

  • 使用 PHP 的内置 ReflectionClass

     class Weekday
     {
     	/**
     	 * Monday
     	 */
     	const MONDAY = 1;
    
     	/**
     	 * Tuesday
     	 */
     	const TUESDAY = …
     }
    
     $reflected = new \ReflectionClass(Weekday::class);
     $constant = $reflected->getConstant('MONDAY');
    
     var_dump($constant);
     // int(1)
  • 使用 \Bramus\Reflection\ReflectionClass

     class Weekday
     {
     	/**
     	 * Monday
     	 */
     	const MONDAY = 1;
    
     	/**
     	 * Tuesday
     	 */
     	const TUESDAY = …
     }
    
     $reflected = new \Bramus\Reflection\ReflectionClass(Weekday::class);
     $constants = $reflected->getConstant('MONDAY');
    
     var_dump($constant);
     // object(Bramus\Reflection\ReflectionClassConstant)#40 (2) {
     //   ["name"]=>
     //   string(6) "MONDAY"
     //   ["class"]=>
     //   string(7) "Weekday"
     //   ["docComment":"Bramus\Reflection\ReflectionClassConstant":private]=>
     //   object(phpDocumentor\Reflection\DocBlock)#86 (7) {
     //     …
     //   }
     // }

ReflectionClassConstant

\ReflectionClassConstant 相比,\Bramus\Reflection\ReflectionClassConstant 工作方式完全相同,但它将在调用 getDocComment()

  • 返回一个 \phpDocumentor\Reflection\DocBlock 实例 (而不是字符串)
  • 在需要以 \ReflectionClassConstant::getDocComment() 返回的内容进行访问时,提供了一个 getDocCommentString() 方法。
  • \Bramus\Reflection\ReflectionClassConstant 实例上提供了一个 getSummary() 简写。
  • \Bramus\Reflection\ReflectionClassConstant 实例上提供了一个 getDescription() 简写。

其他反射类

尚未提供其他反射类。将来可能会提供。

测试

bramus/reflection 配套使用 PHPUnit ~8.0 的单元测试。

  • 如果已全局安装 PHPUnit,请运行 phpunit 以运行测试。
  • 如果没有全局安装 PHPUnit,请通过运行 composer install --dev 在本地通过 Composer 安装它。通过调用 ./vendor/bin/phpunit 或使用 composer 脚本 composer test 运行测试。
$ composer test

许可证

bramus/reflection 在 MIT 公共许可证下发布。有关详细信息,请参阅附带的 LICENSE 文件。