Introduction and application of PHP abstract method and abstract class abstract keyword

  • 2021-07-22 09:09:53
  • OfStack

PHP abstract method and abstract class abstract keyword
The abstract keyword is used to define abstract methods and abstract classes.

Abstract method

An abstract method is a method without a method body, which means that the method is declared without {} brackets and their contents, but directly ends with a semicolon after the method name.

The abstract keyword is used to define abstract methods, syntax:
abstract function function_name();

Abstract class

As long as one method in a class is an abstract method, then the class is defined as an abstract class. Abstract classes are also defined by the abstract keyword.
Abstract classes do not produce instance objects, usually abstract methods are used as templates for subclass method overloads, and methods in inherited abstract classes are implemented. In fact, abstract classes are introduced to facilitate inheritance.

Examples:


<?php
abstract class AbstractClass{
// Define abstract methods
abstract protected function getValue();
// Common method
public function printOut(){
print $this->getValue()."<br />";
}
}
class ConcreteClass extends AbstractClass{
protected function getValue(){
return " Implementation of abstract method ";
}
}

$class1 = new ConcreteClass;
$class1->printOut();
?>

In this example, the parent class defines the abstract method and the implementation of the method, but the actual content is defined in the subclass.


Related articles: