class SingleTon
{
private static $instance;
private function __construct()
{
}
public function getInstance() {
if($instance === null) {
$instance = new SingleTon();
}
return $instance;
}
}
The above code depicts Singleton pattern from this article. http://www.hiteshagrawal.com/php/singleton-class-in-php-5
I did not understand one thing. I load this class in my project, but how would I ever create an object of Singleton initially. Will I call like this Singelton :: getInstance()
Can anyone show me an Singleton class where database connection is established?
Yes, you have to call using
The first time it will test the private var
$instance
which is null and so the script will run$instance = new SingleTon();
.For a database class it's the same thing. This is an extract of a class which I use in Zend Framework:
Note: The pattern is Singleton, not SingleTon.
An example of how you would implement a Singleton pattern for a database class can be seen below:
You would make use of the class in the following manner:
And for reference, the
Singleton
interface would look like:A few corrections to your code. You need to ensure that the getInstance method is 'static', meaning it's a class method not an instance method. You also need to reference the attribute through the 'self' keyword.
Though it's typically not done, you should also override the "__clone()" method, which short circuits cloning of instance.
One thing to not is that if you plan on doing unit testing, using the singleton pattern will cause you some difficulties. See http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html