As @raina77ow noted in a comment, this is called the Singleton pattern. Here's some explanation:
The point of being a Singleton is that no calling code can create more than one $db
. And to provide global access from anywhere in your code to the created $db
.
Static class variables exist as exactly one instance per class. Therefore you can't create multiple $db
connections even if you could instantiate this class as an object.
Since there's no purpose to instantiating the class as an object (that would only be useful if the class had non-static variables that existed per object instance), the class constructor is not needed. To prevent calling code from being tempted to call new
, the constructor is made private. (Strictly speaking, there would be no harm in doing so, because the only class variables are static anyway.)
Note that your implementation is missing the magic __clone
and __wakeup
methods. Without these your Singleton can still be cloned and unserialized. So technically, your Singleton is not enforcing singularity properly.
Here are some additional thoughts:
Singleton classes (or any classes with static usage) are notoriously difficult to integrate into automated testing. Since they're static, you can initialize them once and they retain their state for the duration of your test suite. If you use non-static classes, you can re-initialize them each time you use new
to instantiate a new object.
An alternative design is to use a Registry pattern, and some kind of bootstrap for your application that creates a non-static db instance and stores it in the registry.
If you do use Singleton, it's sometimes recommended to declare the Singleton class final
so no subclasses can override the behavior or get access to the private data.
Your database credentials are hard-coded as private data in the class definition. I wouldn't do that. If your Apache PHP handler gets misconfigured, users could see your PHP source code, and then they'd have your database password. Put the database connection parameters into a config file, and store the config file outside your Apache document root.
Outputting the db connection error message verbatim can reveal information to users. Log the PDO error message, but put out a friendly message for users like "we're experiencing a problem, please notify the site administrator."
You don't need to terminate PHP blocks with ?>
in a class definition file. It adds a risk that you could have a space or a newline after the close, which will become whitespace in your application and throw off your layout. Those types of errors are maddening to track down.