Tuesday, January 11, 2011

Singleton in php

The following php code create a Singleton class call "DataManager":


class DataManager
{
    // Hold an instance of the class
    private static $mInstance;

    // A private constructor; prevents direct creation of object
    private function __construct()
    {
      
    }

    // The singleton method
    public static function getSingleton()
    {
        if (!isset(self::$mInstance)) {
            $c = __CLASS__;
            self::$mInstance = new $c;
        }

        return self::$mInstance;
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }
  
    public function doSomething()
    {
    }

}

To call the doSomething() function of the DataManager singleton, using the following code
DataManager::getSingleton()->doSomething()

No comments:

Post a Comment