1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
/**
* Created by PhpStorm.
* User: 小灰灰
* Date: 2022-04-26
* Time: 21:53:40
* Info:
*/
namespace support\lib;
Env::load();
class Env
{

/**
* 环境变量数据
* @var array
*/
protected static $data = [];

/**
* 读取环境变量定义文件
* @access public
*
* @param string $file 环境变量定义文件
*
* @return void
*/
public static function load($file = '.env')
{
if ( ! is_file($file)) {
return;
}
$env = parse_ini_file($file, true);
self::set($env);
}

/**
* 获取环境变量值
* @access public
*
* @param string $name 环境变量名
* @param mixed $default 默认值
*/
public static function get($name = null, $default = null)
{
if ($name == null) {
return self::$data;
}
$name = strtoupper($name);
$name = strtoupper(str_replace('.', '_', $name));
if (isset(self::$data[$name])) {
return self::$data[$name];
}

return $default;
}

/**
* 设置环境变量值
* @access public
*
* @param string|array $env 环境变量
* @param mixed $value 值
*
* @return void
*/
public static function set($env, $value = null)
{
if (is_array($env)) {
$env = array_change_key_case($env, CASE_UPPER);
foreach ($env as $key => $val) {
if (is_array($val)) {
foreach ($val as $k => $v) {
self::$data[$key.'_'.strtoupper($k)] = $v;
}
} else {
self::$data[$key] = $val;
}
}
} else {
$name = strtoupper(str_replace('.', '_', $env));
self::$data[$name] = $value;
}
}
}

使用方法:

1
2
3
use support\lib\Env;

Env::get('SQL.DB_DEFAULT', 'mysql')

.env 文件:

1
2
3
4
5
6
7
8
[SQL]
DB_DEFAULT = mysql
HOSTNAME = 127.0.0.1
DATABASE = database
DBNAME = root
DBPASS = 123456
HOSTPOINT = 3306
PREFIX = cmf_