Base.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * @author mybsdc <[email protected]>
  4. * @date 2021/10/22
  5. * @time 17:13
  6. */
  7. namespace Luolongfei\Libs;
  8. class Base
  9. {
  10. /**
  11. * @var array
  12. */
  13. private static $instances = [];
  14. /**
  15. * 添加单例
  16. *
  17. * @param string $className
  18. * @param bool $overwrite
  19. *
  20. * @throws \Exception
  21. */
  22. public static function addInstance(string $className, bool $overwrite = false)
  23. {
  24. if (isset(self::$instances[$className]) && !$overwrite) {
  25. throw new \InvalidArgumentException(sprintf(lang('100053'), $className));
  26. }
  27. if (!class_exists($className)) {
  28. throw new \Exception(sprintf(lang('100054'), $className));
  29. }
  30. $instance = new $className();
  31. self::$instances[$className] = $instance;
  32. }
  33. /**
  34. * 获取对象实例
  35. *
  36. * @param ...$params
  37. *
  38. * @return mixed
  39. * @throws \Exception
  40. */
  41. public static function getInstance(...$params)
  42. {
  43. $className = isset($params[1]) && $params[1] === 'IS_MESSAGE_SERVICE' ? $params[0] : static::class;
  44. if (!isset(self::$instances[$className])) {
  45. self::addInstance($className);
  46. // 由于自 php8 开始,is_callable 函数中如果使用类名,将不再适用于非静态方法,非静态方法必须使用对象实例,故只能将 init 从基类的
  47. // 普通构造函数迁移至此处,既可以实现单次调用非静态初始化方法,又不影响继承
  48. if (is_callable([self::$instances[$className], 'init'])) {
  49. self::$instances[$className]->init(...$params);
  50. }
  51. }
  52. return self::$instances[$className];
  53. }
  54. private function __construct()
  55. {
  56. }
  57. private function __clone()
  58. {
  59. }
  60. }