A class designed only as a parent from which sub-classes may be derived.
- Abstract classes are classes that may contain abstract method(s).
- An abstract method is a method that is declared but contains no implementation.
- If a class contains an abstract method, the class itself must be declared as abstract.
- Abstract classes can not be instantiated, and require subclasses to provide implementations for the abstract methods.
To make a class abstract, add the keyword abstract
before the class name in the class definition.
<?php abstract class Products { protected $name; protected $type; public function __construct($name, $type){ $this->type = $type; $this->name = $name; } public function getType() { return $this->type; } public function getName() { return $this->name; } //In an abstract class, any method can be declared abstract abstract public function getPrice(); }
Abstract classes can not be instantiated, so we’ll extend it by making a child class Paper
. An abstract method getPrice
declared in the abstract class. A method marked abstract in the parent’s class declaration must be defined by the inherited (child) class.
<?php class Paper extends Products { public function getPrice() { $a = [ 'A4' => ['80g' => 8.49, '100g' => 10.49], 'Letter' => ['80g' => 8.99, '100g' => 10.99] ]; return $a[$this -> name][$this -> type]; } } $product = new Paper('A4','80g'); echo $product->getPrice(); # Prints: 8.49 $product = new Paper('Letter','100g'); echo $product->getPrice(); # Prints: 10.99
So a class that extends an abstract class must implement all abstract methods. The implementing method should also require the same number of arguments as the abstract method or you’ll receive a fatal error message.
For example, the abstract method getPrice
in our abstract class Products
does not have any argument, if you declare the argument when implementing the method, a fatal error will occur:
<?php class Paper extends Products { public function getPrice($a) { // ... } } # Fatal error: Declaration of Paper::getPrice($a) must be compatible with Products::getPrice()
PHP OOP Tutorials: