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:
When inheriting an abstract class, the subclass must define all abstract methods in the parent class;
In addition, the access control of these methods must be the same as that in the parent class (or more relaxed).
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 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!