php singleton
Singleton allows you to create an object that has only one instance, e.g. database class to avoid multiple connections:
class Database {
private static $instance = false;
private function __construct() {
$this->connect();
}
public static function getInstance() {
if(self::$instance == false) {
self::$instance = new Database();
}
return self::$instance;
}
public function connect() {
// create connection
}
Then, instead of creating an object, you call a static method of Database class:
$db = Database::getInstance();
Notice the private constructor and $instance variable inside a class.
Written by Krzysztof
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#