Home  >  Article  >  Backend Development  >  Detailed explanation of php abstract classes

Detailed explanation of php abstract classes

小云云
小云云Original
2018-03-15 10:09:521881browse

PHP 5 supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class must be declared abstract if at least one method in it is declared abstract. A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation.

Note:

  1. When inheriting an abstract class, the subclass must define all abstract methods in the parent class;

  2. In addition, the access control of these methods must be the same as that in the parent class (or more relaxed).

  3. The calling method of the method must match, that is, the type and the number of required parameters must be consistent.

Example:

<?phpabstract class AbstractClass{
    // 我们的抽象方法仅需要定义需要的参数
    abstract protected function prefixName($name);}class ConcreteClass extends AbstractClass{

    // 我们的子类可以定义父类签名中不存在的可选参数
    // 该访问控制只能是公有的(public)或受保护(protected)的
    public function prefixName($name, $separator = ".") {
        if ($name == "Pacman") {            $prefix = "Mr";
        } elseif ($name == "Pacwoman") {            $prefix = "Mrs";
        } else {            $prefix = "";
        }        return "{$prefix}{$separator} {$name}";
    }
}$class = new ConcreteClass;echo $class->prefixName("Pacman"), "\n";echo $class->prefixName("Pacwoman"), "\n";?>

Result:

Mr. Pacman
Mrs. Pacwoman

Analysis:

Although the subclass defines an optional parameter , which is not included in the declaration of the abstract method of the parent class, but does not conflict with the third point in the note

Related recommendations:

Detailed explanation of the implementation method of php abstract class

phpDetailed explanation of the differences between abstract classes and interfaces and selection of examples

phpDetailed explanation of abstract class feature examples

The above is the detailed content of Detailed explanation of php abstract classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn