Reputation: 560
I have a little question, I think it is a stupid question. I'm starting to coding OOP and I saw a lot of classes on the internet that had this piece of code:
public static $istance;
public function __construct(){
//some code...
$this->instance = $this;
}
public function get_instance(){
return $this->instance;
}
My question is: what is the reason?
Upvotes: 1
Views: 1123
Reputation: 1500
This is the bad realisation of singleton http://en.wikipedia.org/wiki/Singleton_pattern.
Shortly: Singleton is design pattern, which guarantees that the single-threaded application will be the only instance of the class with a global access point.
Right realisation
class Singleton {
protected static $instance;
private function __construct(){ /* ... @return Singleton */ }
private function __clone() { /* ... @return Singleton */ }
private function __wakeup() { /* ... @return Singleton */ }
public static function getInstance() {
if ( !isset(self::$instance) ) {
self::$instance = new self();
}
return self::$instance;
}
public function doAction() { /* ... */ }
}
Call instance
Singleton::getInstance()->doAction();
Upvotes: 5
Reputation: 14868
Although the context of the code snippet you provided is not distinctively clear to me, it looks like they're implementing a singleton pattern in that piece of code.
If you'd like to know more about the singleton pattern generally, check it out here.
Sample implementation of singleton pattern in PHP can be found here.
What is the essence of this pattern?
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only one instance of a particular class. The singleton pattern enables us to do this.
Upvotes: 1
Reputation: 380
I think what you are getting at here is the singleton pattern. The "some code" part of your example would check first for a presence of an existing class having been already instantiated. what code would go in get instance would be a check for the class first in the construct.
if ($this->instance === null) {
$this->instance = new YourClass();
}
return $inst;
This pattern has been widely overused, but it is useful for database connections, for instance, where you would only want one instance of the connection floating around at a time. Contrast this to Factory pattern where multiple objects can be spawned.
Upvotes: 0
Reputation: 14599
It looks like the Singleton pattern. It ensure we'll have only one instance of the class.
However, in general the constructor is private
, to prevent clients to create new instances themselves.
Upvotes: 0