Home  >  Article  >  Backend Development  >  What is an abstract class in php? how to use?

What is an abstract class in php? how to use?

王林
王林forward
2019-09-05 15:00:273263browse

What is an abstract class in php? how to use?

Abstract class: At least one method in a class is abstract, we call it an abstract class.

Requirements:

1. There must be at least one abstract method in a class

2. Abstract methods are not allowed to have {}

3. Abstract

must be added in front of the abstract method. Example: Adding abstract

in front of the class defines an abstract class of Human. There is an abstract method in the abstract class. When executed, an error is reported.

Fatal error: Abstract function Human::getInfo() cannot contain body

Abstract methods cannot have a text part (no method body), and the curly braces need to be removed

 getUserInfo();
    $Tom -> getWalletInfo ();
?>

Note:

1. Abstract classes cannot be Instantiated, can only be inherited.
2. In the inherited derived class, all abstract methods must be overloaded before instantiation

abstract class Human {
    public abstract function getUserInfo ();
    public abstract function getWalletInfo ();
}

class Student extends Human {
    public function getUserInfo () {
        echo 'getinfo';
    }
    
    // public function getWalletInfo () {
    //     echo 'getwalletInfo';
    // }
}

$Tom = new Student();

For example, if the derived class lacks a getWalletInfo() method, new will fail

The meaning of abstract class: When a derived class inherits an abstract class, it must use the naming rules of the abstract class to establish methods, otherwise the derived class is not allowed to be instantiated. In fact, it declares a specification to achieve The purpose of normative methods.

If you want to know more related content, please visit the php Chinese website: PHP video tutorial

The above is the detailed content of What is an abstract class in php? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete