crowdstar / reflection
允许直接访问受保护的/private属性和调用受保护的/private方法。
2.0.0
2023-05-05 00:00 UTC
Requires
- php: >=8.0
Requires (Dev)
- phpunit/phpunit: ~9.0
README
A PHP reflection library to directly access protected/private properties and call protected/private methods. Static properties and methods can also be accessed/invoked from a class directly.
This library works with major versions of PHP from 5.3 to 8.2.
安装
对于PHP 8.0+,请使用版本2.0
composer require crowdstar/reflection:~2.0.0
对于旧版本的PHP(PHP 5.3到PHP 7.4),请使用版本1.0
composer require crowdstar/reflection:~1.0.0
如何使用
提供了三个静态方法来访问对象/类的受保护的/private属性和调用受保护的/private方法。
CrowdStar\Reflection\Reflection::getProperty()
: 获取属性当前值。CrowdStar\Reflection\Reflection::setProperty()
: 设置属性的新值。CrowdStar\Reflection\Reflection::callMethod()
: 调用类/对象的方法。
以下是一个示例代码,展示了如何使用它们。
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use CrowdStar\Reflection\Reflection; class Helper { private string $key; private static string $keyStatic; private function get(): string { return 'Private method invoked.'; } private static function getStatic(int $i, int $j): string { return "Private static method invoked with parameter {$i} and {$j}."; } } $helper = new Helper(); // Access properties and invoke methods from objects. Reflection::setProperty($helper, 'key', 'Set value to a private property.'); echo "Output 1: ", Reflection::getProperty($helper, 'key'), PHP_EOL; echo "Output 2: ", Reflection::callMethod($helper, 'get'), PHP_EOL, PHP_EOL; // Access static properties and invoke static methods from objects. Reflection::setProperty($helper, 'keyStatic', 'Set value to a private static property.'); echo "Output 3: ", Reflection::getProperty($helper, 'keyStatic'), PHP_EOL; echo "Output 4: ", Reflection::callMethod($helper, 'getStatic', [1, 2]), PHP_EOL, PHP_EOL; // Static properties and methods can also be accessed/invoked from a class directly. Reflection::setProperty(Helper::class, 'keyStatic', 'Set another value to a private static property.'); echo "Output 5: ", Reflection::getProperty(Helper::class, 'keyStatic'), PHP_EOL; echo "Output 6: ", Reflection::callMethod(Helper::class, 'getStatic', [3, 4]), PHP_EOL; ?>