Extending singletons in PHP

前端 未结 6 587
春和景丽
春和景丽 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条回答
  •  旧时难觅i
    2021-01-30 12:03

    I have found a good solution.

    the following is my code

    abstract class Singleton
    {
        protected static $instance; // must be protected static property ,since we must use static::$instance, private property will be error
    
        private function __construct(){} //must be private !!! [very important],otherwise we can create new father instance in it's Child class 
    
        final protected function __clone(){} #restrict clone
    
        public static function getInstance()
        {
            #must use static::$instance ,can not use self::$instance,self::$instance will always be Father's static property 
            if (! static::$instance instanceof static) {
                static::$instance = new static();
            }
            return static::$instance;
        }
    }
    
    class A extends Singleton
    {
       protected static $instance; #must redefined property
    }
    
    class B extends A
    {
        protected static $instance;
    }
    
    $a = A::getInstance();
    $b = B::getInstance();
    $c = B::getInstance();
    $d = A::getInstance();
    $e = A::getInstance();
    echo "-------";
    
    var_dump($a,$b,$c,$d,$e);
    
    #object(A)#1 (0) { }
    #object(B)#2 (0) { } 
    #object(B)#2 (0) { } 
    #object(A)#1 (0) { } 
    #object(A)#1 (0) { }
    

    You can refer http://php.net/manual/en/language.oop5.late-static-bindings.php for more info

提交回复
热议问题