PHP MySQL tutorial

Abstract Class in PHP

An abstract class in PHP is a class which cannot be instantiated i.e. we cannot create object of the abstract class. Abstract class usually acts as a base class and is used for inheritance purposes. An abstract class has at least one member function that is marked as abstract. The class which inherits the abstract class must implement the functions of the parent class that are marked abstract. Have a look at the following example to see how abstract classes can be defined and inherited in PHP.

        //Implementing abstract function in child class
         function displayMessage()
            echo "This is a random message.";

    $child = new ChildConcrete();
    $child -> displayName();
    $child -> displayMessage();

Download the code
Run the code

In the above code an parent abstract class named ParentAbstract has been defined. To define a class and function as abstract, the keyword abstract is used. This class contains two abstract methods displayName which is public and displayMessage which is protected. You can see that both these methods have no definitions since implementation for the abstract function is provided by the class which inherts these functions. Next, the ChildConcrete class inherits from the ParentAbstract class. This means that the ChildConcrete class has to provide definition for displayName and displayMessage functions.

Finally the object of the ChildConcrete class has been created and displayName and displayMessage functions are being called to check whether our child class has successfully implemented the parent class abstract methods or not.

<<< Inheritance in Object Oriented PHPMath Functions in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .