简体   繁体   中英

Static methods or not?

I need to develop a small CMS using PHP, and right now I'm trying to figure out the structure.

The CMS will be generated using a set of functions. Things like database functions, caching thingies, internationalization and stuff like this.

I was thinking to do it like this:

  • make the functions non-static methods part of a big "site" class; that way I could run multiple instances of that class. Not sure I would need to do that though..

  • or split the functions into separate classes with static methods

The main problem here is that the CMS should be able to manage multiple small sites, not just one. So either I make all methods static and add a "site switch" function, or make them normal objects which I instantiate based on the site which I want to manage

Which of these would be the best option?

Static methods are generally bad practice. They introduce a lot of potential issues.

1) They introduce hidden dependencies. Code which arbitrarily calls foo::bar() has a dependency on foo and cannot run without foo being defined. The object using foo::bar() will construct correctly but won't be usable if foo is not defined.

2) Statics are globals. Global state is very bad, anything can change the code and its state is unknown. You sacrifice the power and control achieved by OOP encapsulation by using static methods.

3) It's impossible to substitute the functions for a different version

4) It makes unit testing impossible.

For more detailed information and code examples, see this article and this article

I'd definitely suggest using static classes for this job. Going this route will create a pseudo namespace for all of your functions so you don't have to worry about conflicting function names, etc, and it also prevents you from having to pass around an instance of your helper class just to call one of your helper functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM