有没有办法重置特定类的所有静态属性?

2022-01-25 00:00:00 static php phpunit

您可能知道,静态属性使测试变得困难.有没有办法将特定类的所有静态属性重置回初始状态?理想情况下,这不需要为每个类自定义代码,但可以通过继承以一般方式使用,或者完全从类外部使用.

Static properties make testing hard as you probably know. Is there no way to reset all static properties of a particular class back to their initial state? Ideally this would not require custom code for each class, but could be used in a general way by inheritance, or from outside of the class completely.

请不要回复诸如不要使用静态属性"之类的内容.谢谢.

Please do not reply with something like, "don't use static properties". Thanks.

推荐答案

没有.PHP 不保留该信息.

No. PHP does not preserve that information.

我在玩弄 ReflectionClass::getDefaultProperties::getStaticProperties,但它们只返回当前状态.

I was toying around with ReflectionClass and ::getDefaultProperties and ::getStaticProperties, but they only return the current state.

您必须使用默认值创建一个数组,然后手动遍历它们并重置您的类属性.

You will have to create an array with the default values, then manually foreach over them and reset your class attributes.

相关文章