<?php

if ( ! class_exists( 'TX_Singleton' ) ) {
	/**
	 * Class TX_Singleton.
	 *
	 */
	abstract class TX_Singleton {
		/**
		 * @var null
		 *
		 */
		static protected $instances = array();

		/**
		 * TX_Singleton constructor.
		 *
		 */
		abstract protected function __construct();

		/**
		 *
		 * @return self
		 */
		static public function instance() {
			$class = self::get_called_class();
			if ( ! array_key_exists( $class, self::$instances ) ) {
				self::$instances[ $class ] = new $class();
			}

			return self::$instances[ $class ];
		}

		/**
		 * Get called class.
		 *
		 *
		 * @return string
		 */
		private static function get_called_class() {
			if ( function_exists( 'get_called_class' ) ) {
				return get_called_class();
			}

			// PHP 5.2 only
			$backtrace = debug_backtrace();
			if ( 'call_user_func' === $backtrace[2]['function'] ) {
				return $backtrace[2]['args'][0][0];
			}

			return $backtrace[2]['class'];
		}
	}
}
