Skip to content

Instantly share code, notes, and snippets.

@technokid
Created April 11, 2018 18:50
Show Gist options
  • Save technokid/86843f8e956d3b7e81831d5c384f6dbe to your computer and use it in GitHub Desktop.
Save technokid/86843f8e956d3b7e81831d5c384f6dbe to your computer and use it in GitHub Desktop.
Best practice to create php singleton
<?php
trait Singleton {
static private $instance = null;
private function __construct() { /* ... @return Singleton */ } // Protect from creation through new Singleton
private function __clone() { /* ... @return Singleton */ } // Protect from creation through clone
private function __wakeup() { /* ... @return Singleton */ } // Protect from creation through unserialize
static public function getInstance() {
return
self::$instance===null
? self::$instance = new static()//new self()
: self::$instance;
}
}
/**
* Class Foo
* @method static Foo getInstance()
*/
class Foo {
use Singleton;
private $bar = 0;
public function incBar() {
$this->bar++;
}
public function getBar() {
return $this->bar;
}
}
/*
Use
*/
$foo = Foo::getInstance();
$foo->incBar();
var_dump($foo->getBar());
$foo = Foo::getInstance();
$foo->incBar();
var_dump($foo->getBar());
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment