Last Updated: February 25, 2016
· mbunge

13 line singleton implementation

class Singleton {

    private static $instance = null;

    private function __construct(){
        //do something

    public static function getInstance(){
        self::$instance !== null ?: self::$instance = new self();
        return self::$instance;


1 Response
Add your response

It's important to note that this isn't thread safe. This is something similar I always's in c# though, but the idea is the same It's been awhile since I've dug around in php so I don't remember off the top of my head how to lock, but if you can implement it like I did in mine you'd have a pretty good baseline.

The reason this is important is because you plan on using this in a static/global scope, and it's possible for two things to call getInstance right now and create two separate self() objects.

Anyways, good stuff.

over 1 year ago ·