Static classes in PHP via abstract keyword?

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

    There are patterns in OO that are common and well-recognized. Using abstract in an unconventional way may cause confusion (sorry, my some examples are in Java instead of PHP):

    • abstract class - a class meant to conceptualize a common ancestor, but of which actual instances are not meant to exist (e.g. shape is an abstract superclass for rectangle and triangle).
      Commonly implemented by:
      • use abstract modifier on class to prevent direct instantiation, but allow deriving from the class
    • utility class - a class that does not represent an object in the solution space, but rather is a collection of useful static operations/methods, e.g. Math class in Java.
      Commonly implemented by:
      • make class non-derivable, e.g. Java uses the final modifier on class, and
      • prevent direct instantiation - provide no constructors and hide or disable any implicit or default constructors (and copy constructors)
    • singleton class - a class that does represent an object in the solution space, but whose instantiation is controlled or limited, often to insure there is only one instance.
      Commonly implemented by:
      • make class non-derivable, e.g. Java uses the final modifier on class, and
      • prevent direct instantiation - provide no constructors and hide or disable any implicit or default constructors (and copy constructors), and
      • provide a specific means to acquire an instance - a static method (often getInstance()) that returns the only instance or one of the limited number of instances

提交回复
热议问题