PHP OOP Abstract Class

PHP OOP Abstract Class

An abstract class has at least one abstract method and a non-abstract method and declared abstract method can not be implemented inside the abstract class. Implementation of abstract method can be done inside the child class.

Please keep in mind that the declared abstract method inside the child class will have some visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. An abstract method does not have a body hence curry braces {} is not used.

Note:Please keep in mind that an abstract class or abstract method both are defined with the abstract keyword.

How to declare abstract class ?

The abstract keyword is used to define the abstract class.It place just before the class keyword.

Abstract Method Declaration

An abstract method must be declared inside the abstract class by just prepending abstract to the method.Abstract method does not have implementation code hence no requirement to use curly braces {}.

Abstract method's visibility will be either public or protected, but not private.

Abstract classes With non-abstract methods

Abstract class can also have a none abstarct method.This method can be access by child class.Please keep in mind that abstract class can not be instantiate.

PHP Abstraction Rules

Object Creation

Please keep in mind that objects can not be created from abstract classes.

Visiblity Of Child Mehtod

The visiblity of child's method will be similiar or less restricted incomparision to parent's method.

Abstract Method's Visibility Child Method's Visibility
Public Public
Protected Protected or public

Abstract method declared inside the abstract class should not contain private access modifier.

The arguments for child class methods should be the same as the abstract method of the abstract class.

Child class might have a default argument while the abstract class method does not have an argument with a default value.

Examples of Abstract Classes

Let us understand abstract class with the help of an examples.

Parent Abstract Class

Child Classes

Since objects can not be created from an abstract class hence to create objects, we will use child classes.

The Objects

Source Code

Try it now