Last active
August 8, 2024 18:13
-
-
Save broskees/48eb163053124098d7c591dd4b262160 to your computer and use it in GitHub Desktop.
Trait for Singleton Pattern for PHP
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 | |
{ | |
/** | |
* 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