When you don’t want to have more than a single instance of a given class, then the Singleton Design Pattern is used and hence the name is – Singleton. Singleton is the design patterns in PHP OOPs concept that is a special kind of class that can be instantiated only once. If the object of that class is already instantiated then, instead of creating a new one, it gets returned.
Normally when using various objects & classes, define the class only once and then create many objects and instances in our application with each object/instance having its own property. For example, when we are having a class name called “Student” with three attributes – “Fore_Name”, “Middle_Name” and “Sur_Name”. Each instance of that “Student” might or might not be having different values for “Fore_Name”, “Middle_Name” and “Sur_Name”. But if we use a singleton design pattern, there could never be more than a single instance of a given class ever in that given point of the program. The reason is quite simple. Suppose if we want our application to only ever have just one connection in a database, then we have to create a singleton class called “DataBase Connector” whose job is to ensure that there would be only a single DataBase connection in our program. Further meaning that we can access that particular instance quite globally so that we wouldn’t have to get the database connection object between functions get passed so that it could be accessed from each and every place on earth.
The major reason to use the Singleton Design Pattern is that we can use the Singleton Design Pattern object globally and unlike other normal classes, it could only contain one kind of object or one kind of instance. Sometimes, when there is an object that is created only once like the DataBase connection, then the use of Singleton is much more preferable. But note that the constructor method needs to be in private to make the class Singleton.
Below program illustrates the Singleton Design Pattern:
DataBaseConnecter initialize only once bool(true)
- How to create an array with key value pairs in PHP?
- PHP | Collator create() Function
- Different ways to create an Object in C#
- How to create a Collapsed Sidebar?
- Create a Search Bar using HTML and CSS
- How to Create a Tab Image Gallery ?
- How to create an array for JSON using PHP?
- jQuery | Create a div element
- How to create a div element in jQuery ?
- How to create a copy of an object in PHP?
- How to create Radial Menu in CSS ?
- How to create an unordered_map of pairs in C++?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.