Singletons are glorified global variables. The design pattern was created for languages in which global variables are difficult or impossible, or where they are considered bad practice. (In fact, most of the common design patterns are designed for restrictive languages. A great number of them are simply unnecessary in other languages.)
PHP has global variables. PHP global variables are usually a bad practice, but they do exist if you need to use them.
However, there are a few reasons you'd want a Singleton in PHP.
Singletons are useful when the call to getInstance
(the canonical name for the method that returns the single instance of the Singleton) might me made at any point in the script. Up until that point, the object doesn't need to exist. If the object was a global variable instead, either it would have to already exist, or the code trying to reference the object would first need to instantiate it. In fact, anywhere that it could be used, it would need to be instantiated correctly. By centralizing the creation of the single object in getInstance
, you avoid having to create copy-and-paste boilerplate every time you need to reference the object.
Database objects usually get created very early on in the request lifetime, so that specific benefit of Singleton-ness would be wasted.
There are other alternatives to Singleton that can get the job done in other ways. One example is dependency injection, a fancy term for passing external objects that a new object would depend on (such as a database handle) to the object at construction time. However, this can be complicated or annoying. Doing it right might involve injecting a lot of the same objects every single time.
Another alternative is the Registry pattern, which is effectively a container for things that would otherwise be globals. If you don't like global variables, but don't mind them being effectively namespaced, this would be a solution that you'd like.
In the end, pick one way to do it, and stick with that one way throughout your codebase. Personally, I'm a fan of the database object being a global.