hakito / publisher
用于访问受保护/私有类成员的代理。
v1.3
2020-06-20 10:39 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-20 19:45:27 UTC
README
简单代理,用于访问受保护/私有类成员。
其目的是在不重新发明轮子的前提下,让单元测试能够访问私有成员。
此助手使用闭包来访问类的私有成员,而不是使用反射。
安装
composer require hakito/publisher
使用方法
假设你有一个带有私有成员的类
class Target { private $foo = 'secret'; private function bar($arg) { return $arg . 'Bar'; } private static $sFoo = 'staticSecret'; }
创建代理以访问这些成员
$target = new Target(); $published = new hakito\Publisher\Published($target); // Get private property $property = $published->foo; // $property = 'secret'; // Set private property $published->foo = 'outsider'; // $target->foo = 'outsider'; // call private method $name = $published->bar('Saloon'); // $name = 'SaloonBar'; // Optional you can provide a base class in the constructor class Derived extends Target { private $foo = 'derived'; } $derived = new Derived(); $published = new hakito\Publisher\Published($derived, Target::class); $property = $published->foo; // Gets property from Target // $property = 'secret';
访问静态成员
如果你想要访问静态字段或方法,你必须使用类 StaticPublished
$published = new StaticPublished(Target::class); $property = $published->sFoo; // $property = 'staticSecret'
设置字段和调用方法与实例相同。
限制
发布的方法调用无法设置引用参数。
class Target { private function methodWithReferenceArgument(&$arg) { $arg = 'hi'; } } $target = new Target(); $published = new hakito\Publisher\Published($target); $val = 'initial'; $published->methodWithReferenceArgument($val); // $val is still 'initial'
方法调用的返回值不能是引用
class Target { private $_member = []; private function &methodWithReferenceReturnValue($arg) { return $this->_member; } } $target = new Target(); $published = new hakito\Publisher\Published($target); $val = 'initial'; $published->methodWithReferenceReturnValue($val)['new'] = 'value'; // Target::_member is still []