Location: PHPKode > scripts > singleton > singleton/singleton.php
<?php
require_once 'PEAR.php';
define('SINGLETON_ERROR_INVALID_CLASS', 1);
/**
* singleton class manager
*
* @auther Haruki Setoyama <hide@address.com>
* @lisence BSD
* @version 2.0 $Id: singleton.php,v 1.4 2003/10/26 00:51:53 haruki Exp $
* @access public
*/
if (! class_exists('singleton'))
{
    if (!defined('_SINGLETON_GLOBAL')) define('_SINGLETON_GLOBAL', '_SINGLETON');

    class singleton extends PEAR
    {
        /**
        * singleton::getInstance()
        * @param string $name  class name that you want to make singleton.
        * @param bool $init_method  true when useing getInstance() function for initialize
        * @return object  object/PEARError
        * @access public
        */
        function &getInstance($name, $init_method =true)
        {
            $name = trim(strtolower($name));
            if (! isset($GLOBALS[_SINGLETON_GLOBAL][$name]))
            {
                if (! class_exists($name))
                {
                    return singleton::raiseError('Class "'.$name.'" not exist'
                            , SINGLETON_ERROR_INVALID_CLASS);
                }

                $obj = new $name;
                if($init_method != false && is_callable(array($obj, 'getInstance')))
                {
                    $obj =& $obj->getInstance();
                }

                if(! is_object($obj))
                {
                    return singleton::raiseError('fail to instanciate with class "'.$name.'"'
                            , SINGLETON_ERROR_INVALID_CLASS);
                }
                elseif(PEAR::isError($obj))
                {
                    return $obj;
                }

                $GLOBALS[_SINGLETON_GLOBAL][$name] = $obj;
            }
            return $GLOBALS[_SINGLETON_GLOBAL][$name];
        }

        /**
        * singleton::isInstanciated()
        * @param string $name  class name that you want to make singleton.
        * @return bool
        * @access public
        */
        function isInstanciated($name)
        {
            $name = trim(strtolower($name));
            return (! isset($GLOBALS[_SINGLETON_GLOBAL][$name])) ? false : true;
        }

        /**
        * singleton::deleteInstance()
        * @param string $name  class name that you want to make singleton.
        * @return void
        * @access public
        */
        function deleteInstance($name)
        {
            $name = trim(strtolower($name));
            $GLOBALS[_SINGLETON_GLOBAL][$name] = null;
        }
    }
}
?>
Return current item: singleton