Singleton is very basic design pattern.
If the instance is inited once than the class return the same instance.
Example of signleton in php5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <? Class SingletonExample { static private $instance; private function __construct() { } static function getInstance() { if(!Self::$instance) { Self::$instance = new SingletonExample(); } else { return Self::$instance } } public function doHello() { return "Hello World"; } ?> |
Usage Example:
1 2 3 4 5 6 | <? include_once("singleton.class.php"); $single = SingletonExample::getInstance(); echo $single->doHello(); //return "Hello World" ?> |
3 Comments
Congrats on your blog.
Consider looking at this before you choose to use the Singleton pattern:
http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/
Don’t forget to read this before you go and implement a Singleton pattern:
http://moisadoru.wordpress.com/2010/03/02/static-call-versus-singleton-call-in-php/
Thanks Jon