How to deal with global information without creating a Singleton class

Thought it might be useful to summarise some of the points from the comments here. (Note: ‘Singleton’ is a name given to the pattern of storing an instance of a class in a static property of a class, usually the same one, so here ‘singleton’ and ‘static property’ are used more or less interchangeably)

Singleton Dogma

Heed the good advice about singletons and the warnings about bad habits they can get you in, but don’t let that stop you using singletons or static properties. Like using global variables, or not structuring your code well into functions and files, or not commenting your code or naming your variables well; or a thousand other bad programming habits, if you’re not aware of the strucutres you’re using and taking care of good programming habits your life (and maybe other peoples’ lives) will get harder later.

There are only 2 options

Without going outside of the PHP process and its memory, you simply only have two options to share variables between scopes:

  • Global variables
  • Static properties on classes.

There are no other options. Within the WordPress codebase, where you can’t change the structure of swathes of code just to pass your variable around neatly, you therefore have to use one of these two options. The question is not if but how you use them.

Using appropriate complexity

Here are my thoughts on the basic options available. It’s worth considering which of these makes sense for you. Good development without premature optimisation would suggest that you should use the simplest one that supports what you know about your requirements now, with flexibility to change your code if/when you need to.

Get Creative, Use WordPress Ways

Get creative. Access control on top of a configuration class? Use an array or a queue data structure instead of a single variable? Employ WordPress’s filters to pass values around and expose import interfaces in your code to other users?

Some little neat features might save you a ton of heartache to catch situations where, for example:

  • You need to set a value exactly once and read it exactly once
  • You want to allow any number of values to be set from many different places and then read them all in one place
  • You want to debug by seeing who set/get a variable in what order
  • You want to add caching between PHP page loads / sessions
  • You want to make the internals pf your plugin accessible to other people who may want to extend its functionality / content

Leave a Comment