PHP

Singleton Trait

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A reusable trait that turns any class into a lazily-instantiated singleton with a single ::instance() accessor. Throws on clone/wakeup to prevent accidental duplication.
PHP
Raw
<?php
trait Singleton {
    private static ?self $instance = null;

    public static function instance(): static {
        return self::$instance ??= new static();
    }

    public function __clone() { throw new LogicException('Cannot clone a singleton'); }
    public function __wakeup() { throw new LogicException('Cannot unserialize a singleton'); }

    private function __construct() {}   // intentionally not callable from outside
}

final class Config { use Singleton; public string $env = 'prod'; }

echo Config::instance()->env;          // prod
Config::instance()->env = 'dev';
echo Config::instance()->env;          // dev — same instance
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.