web-fu/reflection

v2.3.2 2024-06-21 15:33 UTC

README

Latest Stable Version PHP Version Require Test status Static analysis status Code style status

这个库是PHP反射API的类型安全包装器。

这个库的诞生旨在解决PHP反射API中的类型安全问题。反射API是一个非常强大的工具,但也有一些问题。

例如

  • 原始的 ReflectionClass::getConstant 如果常量不存在或等于 false 则返回 false
  • ReflectionClass::newInstance 返回一个泛型对象,但可以知道对象的类型。
  • 在不同版本的PHP中为反射API添加了新的接口,因此无法以跨版本的方式使用它们。

安装

web-fu/reflection可在Packagist上获取,并可以使用Composer进行安装。

composer require web-fu/reflection

需要PHP 8.0或更高版本。

使用

这个包装器尝试使用与原始Reflection API相同的名称,但使用不同的命名空间。

<?php

require_once __DIR__ . '/vendor/autoload.php';

use WebFu\Reflection\ReflectionClass;
use MyNamespace\MyClass;

$reflection = new ReflectionClass(MyClass::class);
echo $reflection->getName(); // MyNamespace\MyClass
echo $reflection->getShortName(); // MyClass

类型管理

PHP反射API使用不同的类来管理类型:ReflectionTypeReflectionNamedTypeReflectionUnionType

我创建了一个类来管理所有类型:WebFu\Reflection\ReflectionType。我还添加了一个辅助函数来推断PHPDocType,如果已指定。

<?php

require_once __DIR__ . '/vendor/autoload.php';

use WebFu\Reflection\ReflectionClass;

class ClassWithTypes
{
    public int $simple;
    public int|string $union;
    public $noType;
    public ?int $nullable;
    /** @var class-string */
    public string $className;
}

$reflection = new ReflectionClass(MyClass::class);
echo $reflection->getProperty('simple')->getType()->getTypeNames();         // ['int']
echo $reflection->getProperty('union')->getType()->getTypeNames();          // ['int','string']
echo $reflection->getProperty('noType')->getType()->getTypeNames();         // ['mixed']
echo $reflection->getProperty('nullable')->getType()->getTypeNames();       // ['int','null']
echo $reflection->getProperty('nullable')->getType()->getPhpDocTypeNames(); // ['class-string']