PHP oops - Abstract class

What is an abstract class in PHP?

An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code.

An abstract class or method is defined using the abstract keyword.

PHP has abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract.

Abstract Methods declare the method's signature but they cannot define any implementation or body parts.

All abstract methods of Abstract class must be implemented in its child class.

An abstract class also contains Common method (with implementation or body parts)

Child Class must be declared as abstract or implement the remaining abstract methods of abstract class.

PHP Syntax:

 <?php
  abstract class SuperClass {
  abstract public function Method1();
  abstract public function Method2($param1, $param2);

  // Common method
    public function Display() {
       //code to be executed.
    } 

 
  }

class ChildClass extends SuperClass
{  
    //class methods  
}
?>

Example :

<?php
// Code by aryatechno!

abstract class Aryatechno {
public $amount;
public $name;
abstract public function course_name();
abstract public function fees($param1);

// Common method
public function display() {
//code to be executed.
echo "Fee for course $this->name is $this->amount";
}


}

class Courses extends Aryatechno
{

public function course_name()
{
$this->name= "PHP";
}

public function fees($amt)
{
$this->amount=$amt;
}
}

$obj = new Courses;
$obj->fees(10000);
$obj->course_name();

$obj->display();
?>

Output :

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

98395