Use Singleton Pattern in PHP

In this article I explain how to create a singleton pattern in PHP.
  • 1909

Introduction

When your application has a class and the system only needs one instance of a class, and that instance is accessible throughout the program, and whenever the system only needs one instance of a class, but the object (instance) is used by a different application of a system then you can use a Singleton Pattern. Or in other words, if you want to build an application in PHP and the application implements a class that has only one instance, and this instance is to be accessible at the global level then you must use a singleton pattern of your application.

A singleton pattern is used to "Ensure a class has only one instance and provide a global point to retrieve it".

Example of Creating Singleton Pattern in PHP
 

<?php

 class SingletonExample

{

// Hold an instance of the class

private static $instance;
 

// A private constructor; prevents direct creation of object

private function __construct()

{

echo 'I am constructed. '."</br>";

}
 

// The singleton method

public static function singleton()

{

if (is_null(self::$instance)) {

$c = __CLASS__;

self::$instance = new $c;
 

//or self::$instance = new SingletonExample();

}

return self::$instance;

}
 

// Example method

public function GetMe()

{

echo 'Play with Singleton!';

}

}

}
$obj1=SingletonExample::singleton();
$obj1->GetMe();

?> 

Output

singleton-pattern-in-php.jpg

© 2019 DotNetHeaven. All rights reserved.