Singleton Design Pattern in PHP

In this tutorial, I am going to discuss what is singleton design pattern, Why and when to use singleton design pattern in php.

What is Singleton Design Pattern?

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

How to Create Singleton Class in PHP


To create a Singleton class 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.

Magic Methods in PHP.

Singleton Design Pattern 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. When first time we call getInstance() method it will create a new object. After that 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.

Programming Video Tutorials

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.