Skip to content

Instantly share code, notes, and snippets.

@hasinhayder
Last active May 15, 2019 07:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hasinhayder/7487898b7d38aefe3179 to your computer and use it in GitHub Desktop.
Save hasinhayder/7487898b7d38aefe3179 to your computer and use it in GitHub Desktop.
singleton
<?php
class Car{
private $numberPlate;
function __construct(){
$this->numberPlate = "G ".mt_rand(1,1000);
}
function honk(){
echo "Pip Pip. The Numberplate is {$this->numberPlate} \n";
}
}
class RentACar{
static $obj;
public static function getCar(){
/* Don't create a new Car if it's already available */
if(!self::$obj) {
self::$obj = new Car();
}
return self::$obj;
}
}
class Passanger1{
function ride(){
echo "I am Passanger 1. \n";
$myCar = RentACar::getCar();
$myCar->honk();
}
}
class Passanger2{
function ride(){
echo "I am Passanger 2. \n";
$myCar = RentACar::getCar();
$myCar->honk();
}
}
$p1 = new Passanger1();
$p1->ride();
$p2 = new Passanger2();
$p2->ride();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment