...

/

Type Hinting for Interfaces

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
<?php
abstract class Car {
protected $model;
protected $height;
abstract public function calcTankVolume();
}
// Bmw class
class Bmw extends Car {
// Properties
protected $rib;
public function __construct($model, $rib, $height) {
$this -> model = $model;
$this -> rib = $rib;
$this -> height = $height;
}
// Calculate a rectangular tank volume
public function calcTankVolume() {
return $this -> rib * $this -> rib * $this -> height;
}
}
// Mercedes class
class Mercedes extends Car {
// Properties
protected $radius;
public function __construct($model, $radius, $height) {
$this ->model = $model;
$this -> radius = $radius;
$this -> height = $height;
}
// Calculates the volume of cylinder
public function calcTankVolume() {
return $this -> radius * $this -> radius * pi() * $this -> height;
}
}
// Type hinting ensures that the function gets only objects
// that belong to the Car interface
function 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 ...