Skip to content

Instantly share code, notes, and snippets.

@broskees
Last active August 8, 2024 18:13
Show Gist options
  • Save broskees/48eb163053124098d7c591dd4b262160 to your computer and use it in GitHub Desktop.
Save broskees/48eb163053124098d7c591dd4b262160 to your computer and use it in GitHub Desktop.
Trait for Singleton Pattern for PHP
<?php
trait Singleton
{
/**
* Stores the instance, implementing a Singleton pattern.
*
* @var self
*/
private static self $instance;
/**
* The Singleton's constructor should always be private to prevent direct
* construction calls with the `new` operator.
*/
final private function __construct() {}
/**
* Singletons should not be cloneable.
*/
final private function __clone() {}
/**
* Singletons should not be restorable from strings.
*
* @throws Exception Cannot unserialize a singleton.
*/
final public function __wakeup() {
throw new \Exception('Cannot unserialize a singleton.');
}
/**
* This is the static method that controls the access to the singleton
* instance. On the first run, it creates a singleton object and places it
* into the static property. On subsequent runs, it returns the client existing
* object stored in the static property.
*
* @return self
*/
final public static function getInstance(): self
{
if (! isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment