Last active
May 2, 2021 04:35
-
-
Save kangmasjuqi/a1d6822984a57399dfa0ebaa012db789 to your computer and use it in GitHub Desktop.
PHP OOP with Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
ini_set('display_startup_errors', 1); | |
ini_set('display_errors', 1); | |
error_reporting(-1); | |
interface Bird{ | |
public function layEgg($egg_name); | |
} | |
class Chicken implements Bird{ | |
private $name = ''; | |
private $stamp = ''; | |
private $eggs = []; | |
private static $instances = []; | |
public function __construct($name){ | |
$this->name = $name; | |
$this->stamp = date('YmdHis'); | |
} | |
public function layEgg($egg_name) | |
{ | |
$this->eggs[] = new Egg('Chicken', $egg_name, date('YmdHis')); | |
} | |
public function getEggs() | |
{ | |
return $this->eggs; | |
} | |
// singleton | |
public static function getInstance($name) | |
{ | |
$cls = static::class; | |
if (!isset(self::$instances[$cls])) { | |
self::$instances[$cls] = new static($name); | |
} | |
return self::$instances[$cls]; | |
} | |
} | |
class Egg{ | |
private $type = ''; | |
private $name = ''; | |
private $stamp = ''; | |
public function __construct($type, $name, $stamp){ | |
$this->type = $type; | |
$this->name = $name; | |
$this->stamp = $stamp; | |
} | |
public function hatch() | |
{ | |
// using singleton | |
// $new_chicken = Chicken::getInstance("chicken hatched from ".$this->name); | |
// using traditional creation | |
$new_chicken = new $this->type($this->type." hatched from ".$this->name); | |
return $new_chicken; | |
} | |
} | |
$chicken = new Chicken('Chicken name 1'); | |
for($ii=1;$ii<=2;$ii++){ | |
$chicken->layEgg("child egg ".$ii); | |
} | |
$eggs = $chicken->getEggs(); | |
$childs = []; | |
foreach ($eggs as $egg) { | |
$childs[] = $egg->hatch(); | |
} | |
// using singleton | |
// $chicken2 = Chicken::getInstance('Chicken name 2'); | |
// using traditional creation | |
$chicken2 = new Chicken('Chicken name 2'); | |
echo '<pre>'; | |
var_dump($chicken); | |
var_dump($childs); | |
var_dump($chicken2); | |
echo '</pre>'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment