What are Abstract Classes and Abstract Methods in PHP?
Abstract classes and methods are used when the parent class has a named method, but the task needs to be done by one or more of its child classes.
A class is called an abstract class if it has at least one abstract method. A method that is declared but not written into the code is called an abstract method.
The abstract keyword is used to describe an abstract class or method:
Syntax
<?php
abstract class ParentClass {
abstract public function testMethod1();
abstract public function testMethod2($var_1, $var_2);
abstract public function testMethod3() : string;
}
?>
When a class inherits from an abstract class, the child class method must have the same name and either the same access modifier or one that is less strict. So, if the abstract method is defined as \”protected,\” the child class method must also be defined as either \”protected\” or \”public,\” but not as \”private.\” Also, the number and type of arguments that are needed must be the same. But the child classes may also have arguments that are not required.
So, here are the rules for when a child class inherits from an abstract class:
- The name of the method in the child class must be the same as the name of the method in the parent class.
- The access modifier for the child class method must be the same or less strict than the one for the parent class method.
- There must be the same number of arguments. But the child class may have extra arguments that are not required.
Here\’s a good example:
<!DOCTYPE html>
<html>
<body><?php
// Parent class
abstract class School {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function info() : string;
}// Child classes
class Class1 extends School {
public function info() : string {
return \”This is $this->name!\”;
}
}class Class2 extends School {
public function info() : string {
return \”This is $this->name!\”;
}
}class Class3 extends School {
public function info() : string {
return \”This is $this->name!\”;
}
}// Create objects from the child classes
$class1 = new class1(\”Class1\”);
echo $class1->info();
echo \”<br>\”;$class2 = new class2(\”Class2\”);
echo $class2->info();
echo \”<br>\”;$class3 = new class3(\”Class3\”);
echo $class3->info();
?></body>
</html>
Output
This is Class1!
This is Class2!
This is Class3!