Abstract Class in PHP


In this tutorial, we will learn about the Abstract Class in PHP. In Abstract class we only declare methods and after that, we define those methods in child class. An Abstract class must have at least one abstract method in It and any class which extends to the Abstract class must have implemented (override) the abstract methods in it. Abstract classes and methods in PHP are declared with the help of the abstract keyword.

In case you do not have any idea about Method Overriding. Please click here to follow the tutorial of Method Overriding in PHP.

Please check out the following example program to know how to define abstract class and method in PHP.

Example Program:

<?php 

abstract class Bank{
     public $name;
     public $phone;
    
     function createAccount($name, $phone){
        $this->name= $name;
        $this->phone= $phone;
     }

     abstract function interest();

}

?>

As in the above program, you can see we used abstract keyword with class and method names to make them abstract.

Note! An Abstract class can also contain non Abtract methods in it.

Defining Abstract methods in child class:

<?php 

abstract class Bank{
     public $name;
     public $phone;
    
     function createAccount($name, $phone){
        $this->name= $name;
        $this->phone= $phone;
     }

     abstract function interest();

}

class ChildClass extends Bank{
     
     function interest(){
         echo "Hello $this->name, Interest will be 4%";
     }
     
}

$obj= new ChildClass;
$obj->createAccount("Rahul","123456789");
$obj->interest();


?>

Please Note! We can not instantiate Abstract class.

<?php 

abstract class Bank{
     public $name;
     public $phone;
    
     function createAccount($name, $phone){
        $this->name= $name;
        $this->phone= $phone;
     }

     abstract function interest();

}

class ChildClass extends Bank{
     
     function interest(){
         echo "Hello $this->name, Interest will be 4%";
     }
     
}

//this line will throw an error
//PHP Fatal error: Uncaught Error: Cannot instantiate abstract class Bank
$k = new Bank;

$obj= new ChildClass;
$obj->createAccount("Rahul","123456789");
$obj->interest();


?>

 

 



Spread the love:

Please share this page on social media with your friends..

Facebook share Twitter Linkedin share




Great News! Now you can read all the tutorials on our Android App..

Download Owlbuddy: Learn Programming Tutorials App Now.

Download Owlbuddy: Learn Programming Tutorials