Abstract class in PHP simple example 2020

Abstract class in PHP simple example 2020

Abstract class in PHP simple example 2020



Abstract class in PHP simple example 2020

What is Abstract Class

In Object Oriented Programming Abstract keyword is very useful. If we want to create a class that cannot be instantiated but can be extended then we add “abstract” keyword to that class.





Abstract classes are mainly can be extended but cannot be instantiated. If the keyword extend is added in front of function then child class have to have that function otherwise PHP will generate error. Another thing to notice is if class has abstract function then class should be abstract otherwise we will get error. Let’s see how we define abstract class.



Abstract class example

// Abstract class
abstract class Vehicle{
    public $wheel = '4';
    private $color = 'Red';
    public $fuel = 'Petrol';
    // Abstract function in abstract class
    abstract public function checkFuelConsumption();
}


class Car extends Vehicle{
    // function from parent class
    public function checkFuelConsumption(){
        return $this->fuel;
    }

}
//This will generate error as we cannot instantiate abstract class
$v = new Vehicle();

// Car class must have checkFuelConsumption function as defined as //abstract in parent class
$car = new Car();
echo $car->checkFuelConsumption();

So adding “abstract” keyword matters. If absctract function defined as in code “checkFuelConsumption” defined as abstract. Child class “Car Class” must have this function. As we can see “Car Class” has that function. Hope you got the understanding with concept.