Singleton classes in PHP using traits
Single PHP 5.4 it has been possible to define 'traits'. A trait is a way of grouping functionality together so that it can be used across multiple classes. It is an alternative to multiple inheritance.
This means we can add constants, properties and methods to classes, and still inherit functionality from another class.
The most common example of a singleton is a database connection or driver. Here it is using a trait:
/**
* Define a reusable singleton trait.
*/
trait singleton {
/**
* Store the singleton object.
*/
private static $singleton = false;
/**
* Create an inaccessible contructor.
*/
private function __construct() {
$this->__instance();
}
/**
* Fetch an instance of the class.
*/
public static function getInstance() {
if (self::$singleton === false) {
self::$singleton = new self();
}
return self::$singleton;
}
}
/**
* A dummy database driver.
*/
class MySQLDatabase extends Database {
use singleton;
/**
* Instead of a constructor, put your
* initialisation code here.
*/
public function __instance() {
// Create database connection...
}
}
// Fetch our database driver:
$db = Database::getInstance();
Written by Rowan Lewis
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#