Static classes in PHP via abstract keyword?

后端 未结 10 1978
孤独总比滥情好
孤独总比滥情好 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:45

    If your class is not meant to define some super-type, it should not be declared as abstract, I'd say.

    In your case, I would rather go with a class :

    • That defines __construct and __clone as private methods
      • so the class cannot be instanciated from outside
    • And, this way, your class could create an instance of itself
      • See the Singleton design pattern, about that, btw


    Now, why use a Singleton, and not only static methods ? I suppose that, at least a couple of reasons can be valid :

    • Using a singleton means using an instance of the class ; makes it easier to transform a non-singleton class to a singleton one : only have to make __construct and __clone private, and add some getInstance method.
    • Using a singleton also means you have access to everything you can use with a normal instance : $this, properties, ...
    • Oh, a third one (not sure about that, but might have its importance) : with PHP < 5.3, you have less possibilities with static methods/data :
      • __callStatic has only been introduced in PHP 5.3
      • There is no __getStatic, __setStatic, ...
      • Same for a couple of other Magic methods !
    • Late Static Binding has only been added with PHP 5.3 ; and not having it often makes it harder, when working with static methods/classes ; especially when using inheritance.


    This being said, yes, some code like this :

    abstract class MyClass {
        protected static $data;
        public static function setA($a) {
            self::$data['a'] = $a;
        }
        public static function getA() {
            return self::$data['a'];
        }
    }
    
    MyClass::setA(20);
    var_dump(MyClass::getA());
    

    Will work... But it doesn't feel quite natural... and this is a very simple example (see what I said earlier with Late Static Binding, and magic methods).

提交回复
热议问题