PHP: Creating a singleton class
The singleton pattern has both pros and cons. You should only use it if the class never has to be instantiated, as often is the case with database, registry and debug classes. The advantage is never having to manage instances; the class is easily accessible from everywhere. Click through to see examples.
class output
{
private static $_instance;
private function __construct() {}
private function __clone() {}
/**
* @desc Get singleton instance
* @return output
*/
public static function &getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new self();
}
return self::$_instance;
}
public function println($text)
{
print "$text<br />";
}
}
Let's dissect the code, shall we?
The function getInstance
creates, if neccesary, an instance of the class and saves it to the static, private parameter $_instance
. It then returns a reference to the saved instance, hence the ampersand.
If your IDE supports code suggestions, be sure to keep the function comment up-to-date, especially @return
. This will tell your editor what it should expect to be returned from the function, and will then know what functions and parameters to suggest.
To prevent anyone from making more instances of our class, we declare the functions __construct
and __clone
as private.
Singleton is as simple as that! Now how do we use this class? Example below.
// Oneliner
output::getInstance()->println('print to the screen');
// We may borrow the instance, and since it is
// returned by reference, we always work on the
// same instance
$output = output::getInstance();
$output->println('text text');
$output->println('more text');
That's it! If you have any question, don't hesitate →