Created
April 11, 2018 18:50
-
-
Save technokid/86843f8e956d3b7e81831d5c384f6dbe to your computer and use it in GitHub Desktop.
Best practice to create php singleton
This file contains hidden or 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 | |
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