PHP PHP OOPs

Abstract classes and methods (PHP OOPs)





We use abstract classes and methods when we need to commit the child classes to certain methods that they inherit from the parent class but we cannot commit about the code that should be written inside the methods.

An abstract class is a class that has at least one abstract method. Abstract methods can only have names and arguments, and no other code. Thus, we cannot create objects out of abstract classes. Instead, we need to create child classes that add the code into the bodies of the methods, and use these child classes to create objects.

How to declare classes and methods as abstract?
In order to declare a class as abstract, we need to prefix the name of the class with the abstract keyword.
See the following example:

We put the abstract methods that are also declared with the abstract keyword within the abstract class. Abstract methods inside an abstract class don’t have a body, only a name and parameters inside parentheses.
In the example given below, we create a public abstract method, calcNumMilesOnFullTank(), that is the skeleton for methods that we will create in the child classes. Once created, these methods will return the number of miles a car can be driven on a full tank of gas.










Leave a Reply

Your email address will not be published. Required fields are marked *