Skip to content

Instantly share code, notes, and snippets.

@technoknol
Created September 3, 2017 18:38
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/8903991e6395e92a89d713abb81e2aae to your computer and use it in GitHub Desktop.
Save technoknol/8903991e6395e92a89d713abb81e2aae to your computer and use it in GitHub Desktop.
Typehinting with Abstract class PHP
<?php
// Output :
// 53.454492$
// 55.977413122858$
abstract class Car {
protected $model;
protected $height;
abstract public function calcTankVolume();
}
class Bmw extends Car {
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 extends Car {
protected $radius;
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(Car $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