➔ PHP 5 incorporates the concept of abstract classes and abstract methods.
➔ The abstract class defined is not intended to be used to create an object from it; the abstract class has at least one abstract method that must be initialized to mean an abstract class.
➔ Abstract methods only declare the method name and parameter list (method signature), but do not define the inner executable (nobody like interface methods).
Inherit the abstract class
➔ When a class inherits an abstract class, it must define (implement) all abstract methods in the abstract class that it inherits.
➔ In addition, methods must have the same visibility level defined or higher than the specified visibility in the parent class (public, private, protected)
Example
➔ AbstractClass abstract class definition
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php abstract class AbstractClass { // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "n"; } } ?> |
➔ Creates a ConcreteClass1 child class inheriting AbstractClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php class ConcreteClass1 extends AbstractClass { protected function getValue() { return "ConcreteClass1"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } } ?> |
➔ Creates a ConcreteClass2 child class inheriting AbstractClass
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php class ConcreteClass2 extends AbstractClass { protected function getValue() { return "ConcreteClass2"; } public function prefixValue($prefix) { return "{$prefix}ConcreteClass2"; } } ?> |
➔ Creates $class1 $class2 object
1 2 3 4 5 6 7 8 9 10 | <?php $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue("Foo_") . "n"; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue("Foo_") . "n"; ?> |
➔ Show result
1 2 3 4 5 | ConcreteClass1 Foo_ConcreteClass1 ConcreteClass2 Foo_ConcreteClass2 |