PHP OOP – Abstract Class

A class with at least one abstract method is called an abstract class. Names and arguments are the only things that abstract methods can have; no other code is allowed. As a result, we can’t make objects from abstract classes.

Instead, we must build child classes that include the code in the method body, and then child class is used to generate objects.

Abstract and non-abstract methods can both be found in an abstract class but there should be at least one abstract method.

The abstract keyword is used to define an abstract class or method:

Abstract Class Syntax:

abstract class shape {
  abstract public function triangle();

The following rules apply when a child class inherits from an abstract class:

  • The child class method must have the same name as the parent abstract method, and it must redeclare the parent abstract method.
  • The access modifier for the child class method must be the same or less restrictive. For example, if a method in the parent class is public/protected, the child cannot make that method protected.
  • The number of parameters of function defined in child class must be the same. In addition, the child class may include optional parameters.
abstract class Student {
  // Abstract method with an argument
  abstract protected function Student_info($name);

class Student1 extends Student {
  // The child class may define optional arguments that is not in the parent's abstract method
  public function student_info($name, $department = "CS") {

    return "{$name}{$department}";

$s1 = new Student1;
echo $s1->student_info("Henry  ");