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:

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.

Comments

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.

Hi Aaron,
You are correct will update the script

Leave a comment

(required)

(required)