Skip to content

Instantly share code, notes, and snippets.

@tarranjones
Last active December 4, 2016 21:03
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save tarranjones/ace65294ff651b1f2af330ac77c1842a to your computer and use it in GitHub Desktop.
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