Distinguish interface from abstract class abstract class in PHP

Tram Ho

1. What is Abstract class?

  • The abstract class is simply considered a superclass for all classes with the same nature.
  • Each child class can only inherit directly from one parent class using the extends keyword.
  • Objects of abstract class cannot be instantiated.
  • Methods in abstract class can be abstract methods or not. If the method is abstract, it is only allowed to declare the name but not write the content.
  • Subclasses inheriting from abstract must override abstract methods in them.

For example:

2. What is an interface?

  • Interface is not a class, but a blueprint for classes that have the same way of operation.
  • Can not define properties, initialize the object, but only declare methods in the interface.
  • Methods can only declare names but not write content in them.
  • The methods of the interface must be public.
  • If the class inherits from the interface, it must override all the methods in it.
  • A class can inherit from many different interfaces.

For example

Difference between interface and abstract class

  • All methods in an interface are always (understood) as abstract.
  • Methods in abstract class are abstract or not abstract.
  • It is possible to implements many interfaces but cannot extend many classes directly.
  • The methods in the interface must always be public, other than the abstract class can be public, private or protected.

Similarity between interface and abstract class

  • Cannot create a variable of type interface or abstract class.
  • If the method is abstract, it must be declared in the subclass.
  • Both the interface and the abstract class are inheritance.

When to use the interface, when to use abstract class

  • When a group of objects have the same nature inheriting from a class, use abstract class.
  • When a group of objects do not have the same nature but act the same, use the interface.
Share the news now

Source : Viblo