Extending singletons in PHP

前端 未结 6 699
春和景丽
春和景丽 2021-01-30 11:28

I\'m working in a web app framework, and part of it consists of a number of services, all implemented as singletons. They all extend a Service class, where the singleton behavio

6条回答
  •  天命终不由人
    2021-01-30 11:57

    Code:

    abstract class Singleton
    {
        protected function __construct()
        {
        }
    
        final public static function getInstance()
        {
            static $instances = array();
    
            $calledClass = get_called_class();
    
            if (!isset($instances[$calledClass]))
            {
                $instances[$calledClass] = new $calledClass();
            }
    
            return $instances[$calledClass];
        }
    
        final private function __clone()
        {
        }
    }
    
    class FileService extends Singleton
    {
        // Lots of neat stuff in here
    }
    
    $fs = FileService::getInstance();
    

    If you use PHP < 5.3, add this too:

    // get_called_class() is only in PHP >= 5.3.
    if (!function_exists('get_called_class'))
    {
        function get_called_class()
        {
            $bt = debug_backtrace();
            $l = 0;
            do
            {
                $l++;
                $lines = file($bt[$l]['file']);
                $callerLine = $lines[$bt[$l]['line']-1];
                preg_match('/([a-zA-Z0-9\_]+)::'.$bt[$l]['function'].'/', $callerLine, $matches);
            } while ($matches[1] === 'parent' && $matches[1]);
    
            return $matches[1];
        }
    }
    

提交回复
热议问题