Skip to content

Instantly share code, notes, and snippets.

@technoknol
Created September 3, 2017 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save technoknol/dedf42ecfec9157790c926c4d8585023 to your computer and use it in GitHub Desktop.
Save technoknol/dedf42ecfec9157790c926c4d8585023 to your computer and use it in GitHub Desktop.
Type hinting with Interfaces PHP - Example 2
<?php
// output :
// 53.454492$
// 55.977413122858$
interface CarInterface {
public function calcTankVolume();
}
class Bmw implements CarInterface {
protected $model;
protected $height;
protected $rib;
public function __construct($model, $rib, $height)
{
$this -> model = $model;
$this -> rib = $rib;
$this -> height = $height;
}
// Calculates a rectangular tank volume
public function calcTankVolume()
{
return $this -> rib * $this -> rib * $this -> height;
}
}
class Mercedes implements CarInterface {
protected $radius;
protected $model;
protected $height;
public function __construct($model, $radius, $height)
{
$this ->model = $model;
$this -> radius = $radius;
$this -> height = $height;
}
// Calculates the volume of cylinders
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(CarInterface $car, $pricePerGalon)
{
echo $car -> calcTankVolume() * 0.0043290 * $pricePerGalon . "$";
}
$bmw1 = new Bmw('62182791', 14, 21);
echo calcTankPrice($bmw1, 3);
echo PHP_EOL;
$mercedes1 = new Mercedes('12189796', 7, 28);
echo calcTankPrice($mercedes1, 3);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment