Skip to content

Avoid the Singleton

Quick Tips•
December 3, 2026

A static getInstance() singleton hides a piece of global mutable state behind a call you can't see in the constructor. Every class that reaches for it shares the same object, so a test that calls enable('new_checkout') leaves the flag on for every test that runs after it. You can't substitute a fake either, because the dependency never travels through a parameter.

Don't do this

PHP
<?php declare(strict_types=1); namespace App\Reporting; final class FeatureFlags { private static ?self $instance = null; /** @var array<string, bool> */ private array $flags = []; public static function getInstance(): self { return self::$instance ??= new self(); } public function enable(string $name): void { $this->flags[$name] = true; } public function isEnabled(string $name): bool { return $this->flags[$name] ?? false; } } final class CheckoutController { public function store(): void { if (FeatureFlags::getInstance()->isEnabled('new_checkout')) { // ... } } }

Do this instead

Register one shared instance in the container and inject it:

PHP
<?php declare(strict_types=1); namespace App\Reporting; final class FeatureFlags { /** @var array<string, bool> */ private array $flags = []; public function enable(string $name): void { $this->flags[$name] = true; } public function isEnabled(string $name): bool { return $this->flags[$name] ?? false; } }
PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Reporting\FeatureFlags; use Illuminate\Support\ServiceProvider; final class FeatureFlagsServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(FeatureFlags::class); } }
PHP
<?php declare(strict_types=1); namespace App\Reporting; final readonly class CheckoutController { public function __construct(private FeatureFlags $flags) {} public function store(): void { if ($this->flags->isEnabled('new_checkout')) { // ... } } }

The container still hands every class the same FeatureFlags within one application, but the dependency now shows in the constructor. Laravel's TestCase builds a fresh application for each test (refreshApplication()), so the singleton starts empty every time and a flag enabled in one test cannot reach the next. A test that needs specific flags binds its own FeatureFlags before resolving the controller.