Abstract Class

An abstract class is a mix between an interface and a class. It can be define functionality as well as interface.

  • Classes extending an abstract class must implement all of the abstract methods defined in the abstract class.
  • An abstract class is declared the same way as classes with the addition of the ‘abstract’ keyword.

SYNTAX:

abstract class MyAbstract  
{  
    //Methods  
}  
//And is attached to a class using the extends keyword.  
class Myclass extends MyAbstract  
{  
    //class methods  
}  

Example 1

<?php  
abstract class a  
{  
abstract public function dis1();  
abstract public function dis2();  
}  
class b extends a  
{  
public function dis1()  
    {  
        echo "tutorialspro";  
    }  
    public function dis2()  
    {  
        echo "tech";     
    }  
}  
$obj = new b();  
$obj->dis1();  
$obj->dis2();  
?>  

Output:

tutorialsprotech

Example 2

<?php  
abstract class Animal  
{  
    public $name;  
    public $age;  
public function Describe()  
        {  
                return $this->name . ", " . $this->age . " years old";      
        }  
abstract public function Greet();  
    }  
class Dog extends Animal  
{  
public function Greet()  
        {  
                return "Woof!";      
        }  
      
        public function Describe()  
        {  
                return parent::Describe() . ", and I'm a dog!";      
        }  
}  
$animal = new Dog();  
$animal->name = "Bob";  
$animal->age = 7;  
echo $animal->Describe();  
echo $animal->Greet();  
?>  

Output:

Bob,7 years old,and I’m a dog!woof!

Leave a comment