Surfe.be - passive income

What is abstract class in PHP ?

What is abstract class ? Abstract class works almost like interface . If you don’t know about interface then please read this article .what is interface ?  

Abstract classes

  • 1. We declare a abstract class using abstract keyword ..
  • 2 . We can’t create an object of abstract class .
  • 3 . We can access abstract class property from child class using parent keyword.
  • 4 . We can declare non-abstract/abstract method in abstract class .
  • 5 . Abstract class method can’t contains body bar . Only we can override it from sub class .

Hope you have understand all the points. Now let’s see the example .

How to declare abstract class

 abstract class Student{

    // codes goes here
  }

Let’s see examples

 abstract class Student{

    public $name;
    public $age;
  	public function student_details(){  // See it is non- abstract method . We can implement it from here
      echo $this->name . "is" . $this->age . "years old";
    }
  }

  $Student = new Student();
  $Student->name = "Neymar";
  $Student->age = "26";
  $Student->student_details();

If you compile this code then it will generate a fetal error . Because we can not instantiate abstract class property using abstract class object.

 abstract class Student{

    public $name;
    public $age;
  	public function student_details(){
      echo $this->name . "is" . $this->age . " years old";
    }
  }
  class Teacher extends Student {
    public function display(){
      return parent::student_details(); // Used parent::your_abstract_property ; 
    }
  }

  $Teacher = new Teacher();
  $Teacher->name = "Neymar";
  $Teacher->age = "26";
  echo $Teacher->display();

Output :

Neymar is 26 years old

See here We have got no error because you accessed abstract class property from sub class and accessed using sub class object .

Access abstract method from sub class

 abstract class Student{

    public $name;
    public $age;

  	abstract public function student_details(); //we have to override it from subclass . we can't implement it from here 
  }

  class Teacher extends Student {
    public function student_details(){
      return "I am abstract class method output";
    }
  }

  $Teacher = new Teacher();
  echo $Teacher->student_details();

See here how we accessed abstract class method from subclass . Hope all the procedure of abstract class you understand clearly . If you have any confusion about it then leave a comments and share it with your friends.

Leave a comments

LET'S SOCIALITE

Recent Tweets

RECOMMENDED POST