Singleton Design Pattern
is a creational design pattern for Object Oriented Programming.
Singleton Pattern ensures that only one object of that class exists and provides a single point of access to it for any other code.
In these scenerios, we need a Singleton class instance -
- If we don't want to recreat any object second time, then we need to use a way like Singleton.
- If there is a possibility of Memory optimization and one specific class must call one time, then we use singleton pattern.
Creating a Singleton instance is very simple -
<?php
class SingletonPatternExample
{
/**
* Singleton Instance
*
* @var SingletonPatternExample
*/
private static $instance;
/**
* Private Constructor
*
* We can't use the constructor to create an instance of the class
*
* @return void
*/
private function __construct()
{
// Don't do anything, we don't want to be initialized
}
/**
* Get the singleton instance
*
* @return SingletonPatternExample
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
So, we can use this like -
<?php
// We have to call getInstance() static method
$singletonPattern = SingletonPatternExample::getInstance();
// Call our doSomething() method.
$singletonPattern->doSomething();
We can't call Singleton like this -
$singletonPattern = new SingletonPatternExample();
It will throw an exception.
Get More example with Extendable Singleton Pattern with trait and re-usable pattern for PHP -
https://devsenv.com/tutorials/how-to-make-a-singleton-design-pattern-in-php
Top comments (0)