Type Hinting for Interfaces
Learn how to implement type hinting for interfaces.
We'll cover the following...
Interface type hinting
In this lesson, we’ll implement type hinting for both abstract classes and real interfaces.
Press + to interact
<?phpabstract class Car {protected $model;protected $height;abstract public function calcTankVolume();}// Bmw classclass Bmw extends Car {// Propertiesprotected $rib;public function __construct($model, $rib, $height) {$this -> model = $model;$this -> rib = $rib;$this -> height = $height;}// Calculate a rectangular tank volumepublic function calcTankVolume() {return $this -> rib * $this -> rib * $this -> height;}}// Mercedes classclass Mercedes extends Car {// Propertiesprotected $radius;public function __construct($model, $radius, $height) {$this ->model = $model;$this -> radius = $radius;$this -> height = $height;}// Calculates the volume of cylinderpublic function calcTankVolume() {return $this -> radius * $this -> radius * pi() * $this -> height;}}// Type hinting ensures that the function gets only objects// that belong to the Car interfacefunction calcTankPrice(Car $car, $pricePerGallon){return $car -> calcTankVolume() * 0.0043290 * $pricePerGallon . "$";}// Bmw object$bmw1 = new Bmw('62182791', 14, 21);echo "Full rectangular shaped gas tank costs " . calcTankPrice($bmw1, 3);echo "\n";// mercedes Object$mercedes1 = new Mercedes('12189796', 7, 28);echo "Full cylindrical shaped gas tank costs " . calcTankPrice($mercedes1, 3);?>
Explanation
First, we create an abstract class named Car
that both ...