Use of Singleton Pattern in PHP

There are many design patterns we use in our Project, one of the most used design patterns is Singleton. Thats save a lot of efforts of us in OOP.

The main purpose of the Singleton pattern is to deliver a single instance of object no matter how many times you instantiate it.  This saves memory consumption by preventing the creation of multiple instances of an object. Thus Singleton pattern is used to improve the performance of our application.

<?php
class SingletonPattern
{
private static $instance;
public function __construct()
{
if (!self::$instance)
{
self::$instance = $this;
echo “New Instance”;
return self::$instance;
}
else
{
echo “Old Instance”;
return self::$instance;
}
}
}
?>

Now, let check how it works on calling…

<?php
$a = new SingletonPattern();
$b = new SingletonPattern();
$c = new SingletonPattern();
$d = new SingletonPattern();
$e = new SingletonPattern();
?>

Output of the above ;

New Instance
Old Instance
Old Instance
Old Instance
Old Instance

Now, we can check that the it recall its instance after first instance of the object.

Advertisements

2 thoughts on “Use of Singleton Pattern in PHP

  1. Pingback: Use of Singleton Pattern in PHP

  2. Nice article, but there are some mistakes.
    * The implementation is wrong since we can create a new instance of the class. In PHP the instance is not returned by the __construct method like in Java. So there is no point in returning something on it. (Example of implementation: https://gist.github.com/1259831)
    * Singleton in other languages like C++ can be a memory saver and therefore a pattern to use to try to improve performance. In PHP this is completely the opposite, In PHP static methods are much slower than common ones.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s