PHP abstract Abstract Class Definition and Usage Examples

  • 2021-10-13 06:55:53
  • OfStack

This article illustrates the definition and usage of PHP abstract abstract classes. Share it for your reference, as follows:

PHP abstract class application points:

1. Define 1 methods. Subclasses must fully implement all the methods in this abstraction

2. You can't create an object from an abstract class, its meaning is to be extended

3. Abstract classes usually have abstract methods without curly braces

PHP abstract class application focus:

1. Abstract methods do not have to implement concrete functions, but are completed by subclasses

2. When a subclass implements a method of an abstract class, the visibility of its subclass must be greater than or equal to the definition of the abstract method

3. Methods of abstract classes can have arguments or be null

4. If the abstract method has parameters, the implementation of the subclass must have the same number of parameters

Example:


// Function: Abstract classes do not implement concrete methods, which are completed by subclasses. 
// Define abstract classes  abstract
abstract class A{
  //abstract  Defines the method of an abstract class without curly braces. Subclass must implement this abstract method. 
  abstract public function say();
  // Abstract classes can have parameters 
  abstract public function eat($argument);
  // Ordinary methods can be defined in abstract classes. 
  public function run(){
    echo ' This is run Method ';
  }
}
class B extends A{
  // Subclasses must implement the abstract methods of the parent class, otherwise it is a fatal error. 
  public function say(){
    echo ' This is say Method , The abstract method is implemented ';
  }
  public function eat($argument){
    echo ' Abstract classes can have parameters   Output parameters: '.$argument;
  }
}
$b =new B;
$b->say();
echo '<br>';
$b->eat('apple');
echo '<br>';
$b->run();

Run results:

This is the say method, which implements the abstract method
Abstract classes can have parameters. Output parameter: apple
This is the run method

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: