Using classes instead of global functions in functions.php

Using a class for encapsulation is a very common approach by a number of developers for plugins. I do this, and I do find it cleaner. But for plugins. Themes are more procedural by nature.

We don’t do it for default WordPress themes because it raises the barrier to entry. The functions are quite simple. Removing actions tied to classes can be difficult (and potentially buggy in specific circumstances).

Also, a number of functions in the default themes are pluggable. Extending a class and replacing the methods is far more complicated than just defining the function. And while two different aspects of code can replace different functions, you can’t dynamically extend classes. As you pointed out, the need to extend a parent class is definitely a disadvantage.

I considered making Twenty Eleven’s theme options code a class, but never got around to it. That kind of separate, plugin-like functionality seems like a good candidate for encapsulation.

Leave a Comment