PHP Singleton Pattern
Sun, 18 Sep 2011Here is a Singleton pattern in PHP by example. Singleton basically means, 'A single copy'. In order to accomplish this, we must use static methods. Otherwise, the class could be re-instantiated and the "Has Been Called" flag would be reset, destroying our goal. An example of using this could be for loading a database object and being certain its only been loaded once.
My Advice: Use Singleton's sparingly.
/**
* Obviously you don't name a class Singleton, name it for whatever it applies to.
*/
class Singleton
{
/**
* @var boolean $_loaded Whether or not this class has been called
*/
private static $_loaded = false;
/**
* Loads whatever you plan on loading only once
* @return mixed Either False or Object, but you can return anything you like.
*/
public static function load()
{
if (self::$_loaded == true) {
return false;
}
return new itemToLoad();
self::$_loaded = true;
}
}