Skip to content

Instantly share code, notes, and snippets.

@kangmasjuqi
Created May 3, 2021 08:33
Show Gist options
  • Save kangmasjuqi/6b565eaddc2f937a29cc1749a0e7b56b to your computer and use it in GitHub Desktop.
Save kangmasjuqi/6b565eaddc2f937a29cc1749a0e7b56b to your computer and use it in GitHub Desktop.
PHP OOP with Interface - 2
<?php
// INTERFACE
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
interface Vehicle{
public function getCost($d);
}
class Car implements Vehicle{
private $toll_fee = 2000;
private $cost_rate_per_km = 5000;
public function getCost($distance=1){
$cost = ($this->cost_rate_per_km + $this->toll_fee) * $distance;
var_dump("cost using Car is ".$cost);
}
}
class Train implements Vehicle{
private $cost_rate_per_station = 10000;
public function getCost($station=1){
$cost = $this->cost_rate_per_station * $station;
var_dump("cost using Train is ".$cost);
}
}
class Airplane implements Vehicle{
private $initial_cost = 500000;
private $rate_per_transit = 100000;
public function getCost($transit=0){
$cost = $this->initial_cost + $this->rate_per_transit * $transit;
var_dump("cost using Airplane is ".$cost);
}
}
class Mudik{
private $moda = [];
public function __construct($configs){
$this->moda = $configs['moda'];
var_dump("create mudik instance for relation : ".$configs['from']." to ".$configs['to']);
}
public function getCost(Vehicle $vehicle){
$chosen_vehicle = strtolower(get_class($vehicle));
var_dump($this->moda['using_'.$chosen_vehicle]);
return $vehicle->getCost($this->moda['using_'.$chosen_vehicle]['distance']);
}
}
$configs = array(
"from" => "Jakarta", "to" => "Yogya",
"moda" => array(
"using_car" => array("distance" => 500, "measurement" => "km"),
"using_train" => array("distance" => 10, "measurement" => "station"),
"using_airplane" => array("distance" => 0, "measurement" => "transit"),
)
);
$m = new Mudik($configs);
echo '<pre>';
$m->getCost(new Car);
echo "<hr><br>";
$m->getCost(new Train);
echo "<hr><br>";
$m->getCost(new Airplane);
echo '</pre>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment