tags: [env,环境变量,类库]
categories: 学无止境
copyright_author_href: https://www.xiaohuihui.net
copyright_url:
copyright_author:
cover:
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
namespace support\lib; Env::load(); class Env {
protected static $data = [];
public static function load($file = '.env') { if ( ! is_file($file)) { return; } $env = parse_ini_file($file, true); self::set($env); }
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; }
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_
|