Singleton Patten In PHP With Real World Example

Today we will explore one of the php design patterns that is commonly used in most frameworks and languages which is the Singleton Pattern.

 

Ensures that class has only one instance, and provides a global point of access of it.

 

The key point in this pattern is that you define a class with private constructor and public static function that returns instance from the class every time we use it. the private constructor here will disable the default instantiation of the class using new keyword.

As a real world example of it we will create a database class that has global variable and all classes have access to it.

 

In the class above we created a static method getInstance to return instance of the class if it exists or create a new one if it doesn’t exist.

 

To use it

 

Note that if try to create a new instance using the new keyword a Fatal error will appear like that:

Fatal error: Uncaught Error: Call to private DatabaseManager::__construct()

and this happens because of the private constructor



So what is the difference between creating instance using the new keyword and when you use singleton pattern?

To illustrate this lets make the constructor as public and print the object with var_dump():

When you run the above script it will show a new identifier for the class #1, #2, #3 which means the three objects are totally separate:

 

But with singleton pattern method only one identifier #1 is created like this:

As shown above you now understand the power of the singleton pattern, how its created and why it should be used in scenarios like that.

Share this: