Singleton Design Pattern in PHP

In this tutorial, You’ll going to learn what is singleton design pattern, Why and when to use this design pattern in your code.

Singleton Design Pattern

In Singleton Design Pattern, we ensure a class has only one instance and that instance can be accessed globally. The Singleton design pattern restricts the instantiation of a class to one object.

Singleton Design Pattern in PHP

To create a Singleton Pattern we need

1. Static member variable – It acts as a placeholder for the instance of that class

2. Private Constructor – Private constructor prevents direct instantiation of a class.

3. Prevent object cloning by making clone magic method private.

4. Create a static method for global access.

Subscribe Our Tutorials

Get Latest Updates on Facebook

Magic Methods in PHP.

We have discussed some important points regarding singleton design pattern, let’s implement this in our class.

In this example, I have created two variable which is pointing to the same object. The first call will create a new object while any subsequent call will only return the instantiated object.

Let’s create a simple database connection class using Singleton Design pattern.


NOTE – This design pattern is very useful when we required only a single instance of a class for the entire request lifecycle in a web application. You can use this design pattern for your logger class, configuration class etc. where we need only a global access point.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.