Often you have some data and functions you want to use in your application. Perhaps a WordPress theme file that contains some shared data and logic.

The Singleton pattern is a way to create a single instance of a class, and then use that instance throughout your application. When you set some data within that class instance, it will be preserved for use later.

Here’s a base class you can use to create Singleton classes. By extending from this base class, you can avoid repeating these patterns in your child classes.

<?php

namespace Snellcode;

abstract class Singleton {
  protected static $instances = [];
  protected function __construct() {}
  final private function _clone() {}
  public static function getInstance(...$args) {
    $class = get_called_class();
    if (!isset(static::$instances[$class])) {
      static::$instances[$class] = new $class(...$args);
    }
    return static::$instances[$class];
  }
}

To use this base class, you would do something like this:

<?php

namespace Snellcode;

class Theme extends Singleton {
}

When you need to access the Singleton class instance, you can do this:

$theme = \Snellcode\Theme::getInstance();
$theme->foo = "bar";

// show that data will be the same...

$theme2 = \Snellcode\Theme::getInstance();
echo $theme2->foo;

You can use this any place in your application, and the instance will be the same. If you set class properties with some data, you will be able to later use that data. If we just used new Theme without the Singleton pattern, the class instance would be reset to it’s initial state.