Skip to content

Instantly share code, notes, and snippets.

@amacgregor
Last active March 8, 2024 07:25
Show Gist options
  • Save amacgregor/8660951 to your computer and use it in GitHub Desktop.
Save amacgregor/8660951 to your computer and use it in GitHub Desktop.
PHP Singleton pattern example
<?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();
?>
@miloslavkostir
Copy link

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