Last active
October 30, 2025 17:03
-
-
Save UtmostCreator/6dd335ddcb94eda2c3c9fa59d667ead3 to your computer and use it in GitHub Desktop.
most basic example pattern
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 | |
| /* | |
| Singleton, and how the PHP version enforces it: | |
| - Why the name: From the GoF book—“Ensure a class has only one instance, and provide a global point of access to it.” A singleton set has exactly one element; same idea here. | |
| - Private constructor: `private function __construct()` prevents `new Singleton()` from the outside. | |
| - Single stored instance: a private static property (e.g., `private static ?self $instance`) holds the one-and-only object (and allows this propery to be accessed from static method instance()). | |
| - Global access point: a public static accessor (e.g., `instance()`) lazily creates and returns that object. | |
| - No copies: block duplication by making `__clone()` private and throwing in `__wakeup()` (and, if you like, `__serialize/__unserialize`) to prevent cloning/unserialization. | |
| - No subclasses: mark the class `final` so inheritance can’t sneak in extra instances. | |
| the “one instance” is per process/request (e.g., per PHP-FPM worker), not across the whole server. | |
| */ | |
| final class Singleton | |
| { | |
| private static ?self $instance = null; | |
| private function __construct() | |
| { | |
| // Optional: block reflection from making a second instance | |
| if (self::$instance !== null) { | |
| throw new \RuntimeException('Use Singleton::getInstance()'); | |
| } | |
| } | |
| public static function getInstance(): self | |
| { | |
| return self::$instance ??= new self(); | |
| } | |
| // ——— Hardening ——— | |
| // Prevent cloning | |
| private function __clone() {} | |
| // Prevent unserialization (legacy path) | |
| public function __wakeup() | |
| { | |
| throw new \RuntimeException('Cannot unserialize a singleton'); | |
| } | |
| // Prevent serialization (modern path) | |
| public function __serialize(): array | |
| { | |
| throw new \RuntimeException('Cannot serialize a singleton'); | |
| } | |
| public function __unserialize(array $data): void | |
| { | |
| throw new \RuntimeException('Cannot unserialize a singleton'); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment