Skip to content

Instantly share code, notes, and snippets.

@atakde
Created June 27, 2022 20:37
Show Gist options
  • Save atakde/31d2dd8f9cf4021b7584fdc2193ca4b4 to your computer and use it in GitHub Desktop.
Save atakde/31d2dd8f9cf4021b7584fdc2193ca4b4 to your computer and use it in GitHub Desktop.
Design Patterns: Singleton PHP Example
<?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