Skip to content

Instantly share code, notes, and snippets.

@xicond
Last active March 21, 2018 07:08
Show Gist options
  • Save xicond/24304e794b6f729296dfccab74d0f69a to your computer and use it in GitHub Desktop.
Save xicond/24304e794b6f729296dfccab74d0f69a to your computer and use it in GitHub Desktop.
Singleton
<?php
namespace namespaces;
abstract class Singleton
{
// an array of instances. this will keep track of objects already created
private static $instances = [];
abstract protected function __construct();
// this function gets called whenever there is a request for a static function
// that is not present.
// here we assume that the application is looking for the particular service
public static function __callStatic($name, $args)
{
// if no reader is defined yet. set it
if (!isset(self::$instances[$name])) {
$c = "\\namespaces\\Singleton\\{$name}";
self::$instances[$name] = new $c;
}
return self::$instances[$name];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment