-
-
Save amacgregor/8660951 to your computer and use it in GitHub Desktop.
| <?php | |
| /** Example taken from http://www.webgeekly.com/tutorials/php/how-to-create-a-singleton-class-in-php/ **/ | |
| class User | |
| { | |
| // Hold an instance of the class | |
| private static $instance; | |
| // The singleton method | |
| public static function singleton() | |
| { | |
| if (!isset(self::$instance)) { | |
| self::$instance = new __CLASS__; | |
| } | |
| return self::$instance; | |
| } | |
| } | |
| $user1 = User::singleton(); | |
| $user2 = User::singleton(); | |
| $user3 = User::singleton(); | |
| ?> |
better example
`<?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());`
@technokid - your markdown code isn't styled correctly.
CLASS should be new static()!
I use this trait
trait Singleton
{
private static ?self $instance = null;
final private function __construct()
{
// Singleton
}
final public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self;
}
return self::$instance;
}
final public function __clone()
{
throw new \LogicException('Clone is not allowed');
}
final public function __wakeup()
{
throw new \LogicException('Unserialization is not allowed');
}
}then
final class User
{
use Singleton;
}
$user1 = User::getInstance();
$user2 = User::getInstance();
$user3 = User::getInstance();- trait
Singletonhas only one responsibility: to be single - class
Userhas only one responsibility: to represent user - everything is final because an extension from a singleton always gets an instance of the extended class
class Userbetter usefinal class Userand also addprivate function __construct(){}addprivate function __clone(){}andprivate function __wakeup(){}