如何使用PHP反射设置静态属性? [英] How can I use PHP reflection to set a static property?

查看:352
本文介绍了如何使用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

这篇关于如何使用PHP反射设置静态属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆