Getting the name of a child class in the parent class (static context)

前端 未结 9 940
栀梦
栀梦 2020-11-29 20:19

I\'m building an ORM library with reuse and simplicity in mind; everything goes fine except that I got stuck by a stupid inheritance limitation. Please consider the code bel

9条回答
  •  悲&欢浪女
    2020-11-29 20:56

    It appears you might be trying to use a singleton pattern as a factory pattern. I would recommend evaluating your design decisions. If a singleton really is appropriate, I would also recommend only using static methods where inheritance is not desired.

    class BaseModel
    {
    
        public function get () {
            echo get_class($this);
    
        }
    
        public static function instance () {
            static $Instance;
            if ($Instance === null) {
                $Instance = new self;
    
            }
            return $Instance;
        }
    }
    
    class User
    extends BaseModel
    {
        public static function instance () {
            static $Instance;
            if ($Instance === null) {
                $Instance = new self;
    
            }
            return $Instance;
        }
    }
    
    class SpecialUser
    extends User
    {
        public static function instance () {
            static $Instance;
            if ($Instance === null) {
                $Instance = new self;
    
            }
            return $Instance;
        }
    }
    
    
    BaseModel::instance()->get();   // value: BaseModel
    User::instance()->get();        // value: User
    SpecialUser::instance()->get(); // value: SpecialUser
    

提交回复
热议问题