Env.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * 环境变量
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2019/6/2
  7. * @time 17:28
  8. */
  9. namespace Luolongfei\Lib;
  10. use Dotenv\Dotenv;
  11. class Env
  12. {
  13. /**
  14. * @var Env
  15. */
  16. protected static $instance;
  17. /**
  18. * @var array 环境变量值
  19. */
  20. protected $allValues;
  21. public function __construct($fileName)
  22. {
  23. $this->allValues = Dotenv::create(ROOT_PATH, $fileName)->load();
  24. }
  25. public static function instance($fileName = '.env')
  26. {
  27. if (!self::$instance instanceof self) {
  28. self::$instance = new self($fileName);
  29. }
  30. return self::$instance;
  31. }
  32. public function get($key = '', $default = null)
  33. {
  34. if (!strlen($key)) { // 不传key则返回所有环境变量
  35. return $this->allValues;
  36. }
  37. $value = getenv($key);
  38. if ($value === false) {
  39. return $default;
  40. }
  41. switch (strtolower($value)) {
  42. case 'true':
  43. case '(true)':
  44. return true;
  45. case 'false':
  46. case '(false)':
  47. return false;
  48. case 'empty':
  49. case '(empty)':
  50. return '';
  51. case 'null':
  52. case '(null)':
  53. return null;
  54. }
  55. if (($valueLength = strlen($value)) > 1 && $value[0] === '"' && $value[$valueLength - 1] === '"') { // 去除双引号
  56. return substr($value, 1, -1);
  57. }
  58. return $value;
  59. }
  60. }