Last active
March 8, 2024 07:25
-
-
Save amacgregor/8660951 to your computer and use it in GitHub Desktop.
PHP Singleton pattern example
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 | |
/** 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(); | |
?> |
@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
Singleton
has only one responsibility: to be single - class
User
has only one responsibility: to represent user - everything is final because an extension from a singleton always gets an instance of the extended class
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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());`