Singleton Class in PHP

2009
08.13

This is how I create a Singleton class in PHP.

A Singleton class can only be instantiated once. There can only ever be one copy of the class in existence in your program at one time. That is to say, there can only be one object of the type of the Singleton class, in your program.

Static class vs Singleton class

A Singletons member methods or properties can still be accessed via the -> operator, however a static member can only be accessed using the :: operator. The reason behind this is because a Singletons class is still instantiated, the new keyword is still used, with a static class it is never instantiated you just access the methods and properties.

A static class has no initialization, a static class behaves more like a library of methods then an actual object created from a class.

Below is a very simple Singleton class, to instantiate it you call $obj = ClassName::instance() . This will assign the single object to the $obj variable, the instance method returns the object.

You can still initialize data within the class because you can still use the constructor. The instance() method calls the constructor.


	class ClassName
	{
		private $VarName;

		/*
		* The reason the constructor is a private method is to
		* stop a new copy of the class being instantiated.
		*/
		private function __construct()
		{

		}

		/*
		*	Creates a single instance of the class and then returns it
		*  if an instance already exists in the static $instance var then it returns that instead
		*/
		public static function instance()
		{
			/* When a variable is declared as static it will retain its value even after the function
			* where it was defined, goes out of scope.
			*/
			static $instance;

			if ($instance == NULL)
			{
				$instance = new ClassName;
				return $instance;
			}
			else
			{
				return $instance;
			}
		}

		private SomeFunction()
		{

		}
	}

Tags: ,

Comments are closed.