DEV Community

jmau111⚡⚡⚡
jmau111⚡⚡⚡

Posted on

The truth about the truth about static and singletons

As a beginner, you might wonder why there are so many blog posts and threads about the Singleton pattern and why it's considered as a bad practice.

It's pretty much the same for static methods.

Here, I'll try to step back and give you some hints to make your own choices.

Singleton in PHP

class DB {

    private static $instance;

    private function __construct() {}

    final public static function getDB() {
        if (!isset(self::$instance)) {
            self::$instance = new DB();
        }

        return self::$instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

The above class is not a typical PHP singleton implementation, but many of its elements follow common practices. Developers usually store the instance in a static variable and only expose in a unique public static method (getDB()).

The constructor is set to private to explicitly forbid any instanciation with the new keyword.

We do this on purpose to ensure there's only one unique instance any external client or child class can use.

You may see some variants with protected constructors and arrays instead, but let's keep it simple here.

Why [not] using Singletons?

Many articles insist on the single instance and the ability to set a global access why keeping some kind of control (unlike with global variables).

The problem is that every time some people use the term "global," other people think it may kill a dolphin or something else.

While it's usually not that bad, there are pros and cons. In my experience, it can make sense for a database connection, but it's not the ultimate approach.

Besides, you can enforce the same "uniqueness" without using the singleton pattern (e.g., full static classes).

The "truth" is singletons are often misused or overused, which explains why dev teams might want to drop such pattern from their toolbox.

The "meh" critics (¯\(ツ)/¯)

I read that singletons or full static classes are harder to test, but people usually don't explain why and which tests are concerned.

It's easy to understand that unit tests might be harder, as such tests are not meant to address global states, but it does not mean you should never ever use it.

Some cases do require global functionalities or variables. The problems come when you start using them for everything and anything.

Besides, not everything requires an object.

So, what to do?

Use static methods sparingly and singletons even more carefully.

Top comments (0)