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.
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 (or more relaxed) as in the parent class. For example, if an abstract method is declared as protected, then the method implemented in the subclass should be declared as protected or public, and cannot be defined as private. In addition, the method calling methods must match, that is, the type and number of required parameters must be consistent. For example, if a subclass defines an optional parameter that is not included in the declaration of an abstract method of the parent class, there is no conflict between the two declarations. This also applies to constructors since PHP 5.4. Constructor declarations before PHP 5.4 could be different.
Example #1 Abstract class example
abstract class AbstractClass { //强制要求子类定义这些方法 abstract protected function getValue(); abstract protected function prefixValue($prefix); //普通方法(非抽象方法) public function printOut() { print $this->getValue().'<br>'; } } class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcteteClass1"; } public function prefixValue($prefix){ return "{$prefix}ConcreteClass1"; } } class ConcreteClass2 extends AbstractClass { public function getValue(){ return "ConcreteClass2"; } public function prefixValue($prefix){ return "{$prefix}ConcreteClass2"; } } $class1 = new ConcreteClass1; $class1 -> printOut(); echo $class1->prefixValue('Foo_')."<br>"; $class2 = new ConcreteClass2; $class2 -> printOut(); echo $class2->prefixValue('Bar_')."<br>";
Output result:
ConcteteClass1
Foo_ConcreteClass1
ConcreteClass2
Bar_ConcreteClass2
Example #2 Abstract class example
abstract class AbstractClass { //我们的抽象方法仅需要定义需要的参数 abstract protected function prefixName($name); } class ConcreteClass extends AbstractClass { //我们的子类可以定义父类签名中不存在的可选参数 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').'<br>'; echo $class->prefixName('Pacwoman').'<br>';
Output result:
Mr. Pacman
Mrs. Pacwoman