What is the singleton pattern in PHP?

The Singleton pattern is one of the most well-known design patterns in programming. Its purpose is to ensure that a class has only one instance and provide a global access point to it.

In other words, Singleton helps us avoid creating multiple objects of the same class. This is especially useful when working with database connections, global settings, or logging systems.

 

Why use Singleton?

👉 To save system resources.
👉 To avoid inconsistent behavior.
👉 To keep a single point of control.

Imagine you’re working with a database connection. If a new connection is created every time you want to query something, your app will become inefficient. With a Singleton, you can reuse the same instance across your entire project.

How to implement a Singleton in PHP
Let’s look at a simple example to understand how it works.

<?php

class AppConfig {
    private static $instance = null;
    private $config = [];

    // Private constructor to prevent external instantiation
    private function __construct() {
        $this->config = [
            'appName'    => 'MyApp',
            'version'    => '1.0.0',
            'debugMode'  => true
        ];
    }

    // Prevent cloning
    private function __clone() {}

    // Prevent unserialization
    private function __wakeup() {}

    // Static method to get the single instance
    public static function getInstance() {
        if ( self::$instance === null ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getConfig( $key ) {
        return $this->config[ $key ] ?? null;
    }

    public function setConfig( $key, $value ) {
        $this->config[ $key ] = $value;
    }
}

 

How to use it?

<?php

// Get the instance
$config = AppConfig::getInstance();

// Access a config value
echo $config->getConfig( 'appName' ); // Outputs: MyApp

// Update a value
$config->setConfig( 'debugMode', false );

// Somewhere else in the code...
$anotherInstance = AppConfig::getInstance();

echo $anotherInstance->getConfig( 'debugMode' ); // Outputs: false

✔️ As you can see, $configand $anotherInstanceare the same instance.
✔️ Changes made in one place affect the other.

 

When to avoid Singleton

While the Singleton pattern is helpful, it’s not a one-size-fits-all solution. Some developers even consider it an anti-pattern when overused, because:

  • It can make unit testing harder.
  • It can hide real dependencies between classes.
  • Sometimes it’s better to use dependency injection instead of Singleton.

 

The Singleton pattern is ideal when you need a class to have only one globally accessible instance. It’s commonly used for database connections, configuration files, session management, and more.

But remember: use it wisely. A good developer knows when to apply it — and when not to 😉

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x