Detailed explanation of php abstract classes

小云云
Release: 2023-03-21 13:24:01
Original
1865 people have browsed it

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";?>
Copy after login

Result:

Mr. Pacman
Mrs. Pacwoman
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!