Saturday, March 24, 2007

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.


<?php
class Singleton
{
private static $instance;

private function __construct()
{
echo "it's construct.<br />";
}

// prevend users to clone the instance.
private function __clone()
{
trigger_error("error.<br/>", E_USER_ERROR);
}

public static function singleton()
{
if(!isset(self::$instance))
{
$class_name = __CLASS__;
self::$instance = new $class_name;
}
return self::$instance;
}

public function wow()
{
echo "<br/>", "it works, wow!", "<br/>";
}
}
// $s = new Singleton(); //Fatal error: Call to private Singleton::__construct() from invalid context
$s = Singleton::singleton();
var_dump($s);
$s->wow();
?>

No comments :