Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Singleton Classes
<?php
abstract class AbstractSingleton implements SingletonInterface
{
final public static function getInstance()
{
static $instance;
return $instance = $instance ?: new \static();
}
final private function __construct() {}
final private function __clone() {}
final private function __sleep() {}
final private function __wakeup() {}
}
<?php
abstract class AbstractSingleton implements SingletonInterface
{
use SingletonTrait;
}
<?php
interface SingletonInterface {
final public static function getInstance();
}
<?php
trait SingletonTrait {
final public static function getInstance(){
static $instance;
return $instance = $instance ?: new \static();
}
final private function __construct() {}
final private function __clone() {}
final private function __sleep() {}
final private function __wakeup() {}
}
<?php
// usages
class Singleton implements SingletonInterface{
use SingletonTrait;
}
$instance = Singleton::getInstance();
class Singleton extends AbstractSingleton {
}
$instance = Singleton::getInstance();
class Singleton extends AbstractSingletonTrait {
}
$instance = Singleton::getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment