PHP Course : What is a Singleton ?

profile picture

PHP Course : What is a Singleton ?

The Singleton is a design pattern of class creation that garantee instanciating a single object of that class and provide a unique point of access to that object.

A singleton has more or less the same pros and cons than global variables. Even if they are super useful, they decrease code modularity.

You will not be able to use a classe that depends on a singleton in another context. You'll always include the same instance of that class everytime you use it. In general, you'll see the limitation of the implementation when you start creating unit tests.

In other words, a Singleton is a basic PHP class that contains the necessary logic to prevent being instanciated multiple times. You can always have only one instance of that class.

Let's have a look:

´´´php class Singleton { // Hold the class instance. private static $instance = null;

// The constructor is private
// to prevent initiation with outer code.
private function __construct()
{
    // The expensive process (e.g.,db connection) goes here.
}

// The object is created from within the class itself
// only if the class has no instance.
public static function getInstance()
{
    return self::$instance === null ? self::$instance = new self : self::$instance;
}

}

$object1 = Singleton::getInstance(); $object2 = Singleton::getInstance(); $object3 = Singleton::getInstance(); ´´´

´$object1´ and ´$object2´ and ´$object3´ are exactly the same.

But why ?

Good question, and the answer is easy: do you really need to have different instances of a class that is used for only one thing ?

Take a DatabaseConnection class for example, you don't really need to have different instances of that kind of class because it will always be the same.

Same thing for an API connection class, for example.

The use cases are quite limited, but it's still important to know about this concept.

php
class
singleton

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x519e0eaa9bc83018bb306880548b79fc0794cd08

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

recent posts

QBUS - MQTT Quick Tutorial

1
10 months ago

DDOS By Web Crawlers

1
1 year ago

Something Given

1
1 year ago

2024 © My Dynamic Production SRL All rights Reserved.