parent
1b8f72666b
commit
0fccc3b4b1
@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace jrosset\Singleton;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Classe d'implémentation d'un Singleton (création via le constructeur)
|
||||||
|
*/
|
||||||
|
trait TSingleton {
|
||||||
|
/**
|
||||||
|
* @var static|null L'instance. Null si pas encore créée
|
||||||
|
*/
|
||||||
|
private static ?self $singleton_instance;
|
||||||
|
/**
|
||||||
|
* Initialise l'instance'
|
||||||
|
*/
|
||||||
|
protected function __construct () {
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Accès à l'instance du Singleton
|
||||||
|
*
|
||||||
|
* Si l'instance n'a pas encore été créée, elle le sera automatiquement
|
||||||
|
*
|
||||||
|
* @return static L'unique instance du Singleton
|
||||||
|
*/
|
||||||
|
public static final function getInstance (): self {
|
||||||
|
if (!isset(self::$singleton_instance)) {
|
||||||
|
self::$singleton_instance = new static();
|
||||||
|
}
|
||||||
|
|
||||||
|
return self::$singleton_instance;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
/** @noinspection PhpIllegalPsrClassPathInspection */
|
||||||
|
|
||||||
|
require_once __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
use jrosset\Singleton\TSingleton;
|
||||||
|
|
||||||
|
class Test {
|
||||||
|
use TSingleton;
|
||||||
|
|
||||||
|
private int $cpt = 0;
|
||||||
|
|
||||||
|
public function getCpt (): int {
|
||||||
|
return $this->cpt;
|
||||||
|
}
|
||||||
|
public function increment (): void {
|
||||||
|
$this->cpt++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var_dump(Test::getInstance()->getCpt());
|
||||||
|
Test::getInstance()->increment();
|
||||||
|
var_dump(Test::getInstance()->getCpt());
|
||||||
Loading…
Reference in New Issue