Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to reset all static properties of a particular class?

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.

like image 961
dqhendricks Avatar asked Jun 22 '11 23:06

dqhendricks


People also ask

How do you reset a static class in Java?

You can try this. Main MainObject = new Main; MainObject. main(args); It will restart the class again and again until you stop the class.

Can we reinitialize static variable?

Declaring variables only as static can lead to change in their values by one or more instances of a class in which it is declared. Declaring them as static final will help you to create a CONSTANT. Only one copy of variable exists which can't be reinitialize.

Can static properties be inherited?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.


1 Answers

Assuming you're using PHPUnit:

See the PHPUnit Manual section about global state. Static members are covered by this if you have PHP 5.3 or higher. Static members are not part of serialization (in case you wonder).

See as well @backupGlobals and @backupStaticAttributes

like image 95
hakre Avatar answered Nov 11 '22 17:11

hakre