lk4ehw
Last Updated: February 25, 2016
·
3.466K
· psychoticmeow

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();