Static classes in PHP via abstract keyword?

后端 未结 10 1952
孤独总比滥情好
孤独总比滥情好 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条回答
  •  鱼传尺愫
    2021-01-31 19:55

    I wouldnt use an abstract class. Id use something more akin to a singleton with a protected/private constructor as you suggest. There should be very few static properties other than $instance which is the actual registry instance. Recently ive become a fan of Zend Frameworks typical pattern which is something like this:

    class MyRegistry {
    
      protected static $instance = null;
    
      public function __construct($options = null)
      {
      }
    
      public static function setInstance(MyRegistry $instance)
      {
        self::$instance = $instance;
      }
    
      public static function getInstance()
      {
         if(null === self::$instance) {
            self::$instance = new self;
         }
    
         return self::$instance;
      }
    }
    

    This way you get a singleton essentially but you can inject a configured instance to use. This is handy for testing purposes and inheritance.

提交回复
热议问题