web-fu / reflection
反射API
v2.3.2
2024-06-21 15:33 UTC
Requires
- php: ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0
Requires (Dev)
- ext-mbstring: *
- friendsofphp/php-cs-fixer: ^3.13
- infection/infection: ^0.26.16
- phpbench/phpbench: ^1.2
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^5.4
This package is auto-updated.
Last update: 2024-09-12 13:37:29 UTC
README
这个库是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使用不同的类来管理类型:ReflectionType、ReflectionNamedType和ReflectionUnionType。
我创建了一个类来管理所有类型: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']