Singleton Class in PHP 5
With OOPS in PHP 5 the whole bunch of Object Oriented Design Pattern will now come into the PHP 5 programming. The most famous and commonly used is Singleton Class. The main advantage of this Pattern that is allows only one instance of an object to be used across the web application. This pattern is widely used during Database Connection where we want to share only one database connection throughout the Web Application. This article will guide you on using Singleton Class in PHP 5.
< ? class SingleTon { private static $instance; private function __construct() { } public function getInstance() { if($instance === null) { $instance = "First Instance"; } else { $instance = "Second Instance"; } return $instance; } } ?>
Explanation:
- Here i have created an Singleton class. The main feature that makes this class Singleton is that the constructor is declared private
- As the constructor is declared private. This class cannot be instantiated
- Here i have declared an static variable $instance that will hold the object. With the static data type $instance will hold the object till the class is alive
- When getInstance() method is called, it will check whether $instance already has some object, if it already holds some object then it will return that object else assigns an new object to it
Similar Posts
Custom Search
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


For this to be an accurate singleton pattern, the instance needs to be stored in the ‘if’ where $instance is null. Then, of course, $instance needs to be something like self::$instance instead. This way, you store the singleton pattern. In your example, you will continue to get a new object.