Static classes in PHP via abstract keyword?

后端 未结 10 2164
孤独总比滥情好
孤独总比滥情好 2021-01-31 19:00

According to the PHP manual, a class like this:

abstract class Example {}

cannot be instantiated. If I need a class without instance, e.g. for

10条回答
  •  萌比男神i
    2021-01-31 19:46

    From my understanding, a class without instance is something you shouldn't be using in an OOP program, because the whole (and sole) purpose of classes is to serve as blueprints for new objects. The only difference between Registry::$someValue and $GLOBALS['Registry_someValue'] is that the former looks 'fancier', but neither way is really object-oriented.

    So, to answer your question, you don't want a "singleton class", you want a singleton object, optionally equipped with a factory method:

    class Registry
    {
        static $obj = null;
    
        protected function __construct() {
            ...
        }
    
        static function object() {
            return self::$obj ? self::$obj : self::$obj = new self;
        }
    }
    
    ...
    
    Registry::object()->someValue;
    

    Clearly abstract won't work here.

提交回复
热议问题