Singleton.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * @package ActiveRecord
  4. */
  5. namespace ActiveRecord;
  6. /**
  7. * This implementation of the singleton pattern does not conform to the strong definition
  8. * given by the "Gang of Four." The __construct() method has not be privatized so that
  9. * a singleton pattern is capable of being achieved; however, multiple instantiations are also
  10. * possible. This allows the user more freedom with this pattern.
  11. *
  12. * @package ActiveRecord
  13. */
  14. abstract class Singleton
  15. {
  16. /**
  17. * Array of cached singleton objects.
  18. *
  19. * @var array
  20. */
  21. private static $instances = array();
  22. /**
  23. * Static method for instantiating a singleton object.
  24. *
  25. * @return object
  26. */
  27. final public static function instance()
  28. {
  29. $class_name = get_called_class();
  30. if (!isset(self::$instances[$class_name]))
  31. self::$instances[$class_name] = new $class_name;
  32. return self::$instances[$class_name];
  33. }
  34. /**
  35. * Singleton objects should not be cloned.
  36. *
  37. * @return void
  38. */
  39. final private function __clone() {}
  40. /**
  41. * Similar to a get_called_class() for a child class to invoke.
  42. *
  43. * @return string
  44. */
  45. final protected function get_called_class()
  46. {
  47. $backtrace = debug_backtrace();
  48. return get_class($backtrace[2]['object']);
  49. }
  50. }
  51. ?>