如何使用PHP反射设置静态属性?
我正在使用PHPUnit制作一个模拟类进行测试.
I am using PHPUnit to make a mock class for testing.
class Item extends Object {
protected static $_cache;
}
我敢肯定,嘲笑会像这样(如果我错了,请纠正我):
I am pretty certain mocking does something like this ( please correct me if I'm wrong ):
class Mock_Item_randomstring extends Item {
}
当我的Item
的缓存被填充时,它正在检查是否传入的对象是Item
的实例.由于该模拟未明确定义$_cache
,因此它无法通过实例类型检查.
When my Item
's cache gets populated, it's checking to see that the object being passed in is an instance of Item
. Since the mock is not explicitly defining $_cache
, it fails the check for instance type.
PHP根本没有很好地记录反射功能.有没有办法在事发后设置静态变量,这样该类就可以成为
PHP doesn't really document the reflection functions well at all. Is there a way to set the static variable after the fact so the class would become
class Mock_Item_randomstring extends Item {
protected static $_cache;
}
编辑
我玩弄反射方法,遇到了很多问题.这是我很困惑的地方:
I played around with reflection methods and ran into a variety of issues. Here is one that I'm confused about:
$mock = $this->getMock( 'Item', array( '_func' ), array(
$argument1, $argument2
));
$mock = new ReflectionClass($mock);
$mock->staticExpects( $this->exactly(2) )->method( '_func' );
我当时的假设是,反思会复制整个班级.我收到此错误:
Call to undefined method ReflectionClass::staticExpects()
I was under the assumption reflections copy the entire class. I get this error:
Call to undefined method ReflectionClass::staticExpects()
您不必这样做. \Closure::bind
使您可以读取和分配私有和受保护的静态属性.请参见 http://www.php.net/manual/zh/上的示例代码Closure.bind.php
You don't have to. \Closure::bind
lets you read and assign private and protected static properties. See the example code on http://www.php.net/manual/en/closure.bind.php