Created
June 27, 2022 20:37
-
-
Save atakde/31d2dd8f9cf4021b7584fdc2193ca4b4 to your computer and use it in GitHub Desktop.
Design Patterns: Singleton PHP Example
This file contains 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 | |
class Singleton | |
{ | |
private static $instance = null; | |
/** | |
* prevent from creating multiple instances | |
*/ | |
private function __construct() | |
{ | |
} | |
/** | |
* prevent from creating multiple instances | |
*/ | |
private function __clone() | |
{ | |
} | |
/** | |
* prevent from creating multiple instances | |
*/ | |
public function __wakeup() | |
{ | |
} | |
public static function getInstance(): Singleton | |
{ | |
if (!self::$instance) { | |
self::$instance = new Singleton(); | |
} | |
return self::$instance; | |
} | |
} | |
$instance1 = Singleton::getInstance(); | |
$instance2 = Singleton::getInstance(); | |
if ($instance1 === $instance2) { | |
echo "Singleton works.."; | |
} else { | |
echo "Singleton not works."; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment