What is a abstract class and interface in PHP and when would you use them? A layman answer with an example would be great to aid my understanding.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Abstract classes and interfaces are not specific to PHP; they’re features of many modern object-oriented languages.
An abstract class is a class that has one or more unimplemented member functions. You would use one in a situation where you would want a set of classes that have similar behaviors, differing only in a few methods. Each of these classes would derive from the abstract class, and implement the unimplemented methods in the manner that’s appropriate for their specific case.
An interface is similar to an abstract class, but it contains no method implementations, only signatures. A class that implements an interface must implement all of the methods.
A class can implement many interfaces, but can only be derived from one abstract class (or parent class of any sort), since PHP does not support multiple inheritance.
Both abstract classes and interfaces allow for polymorphism; i.e., you can specify a reference as being to an abstract type (which could refer to any instance of class derived from it) or to an object implementing an interface.