[英]What's the best way ro read from a config file in PHP
I know this can be a lot subjective.我知道这可能很主观。 I always worked with frameworks so I am a bit lost when I have to work on something from scratch.我总是使用框架,所以当我必须从头开始做一些事情时,我有点迷茫。
I want to make a class that reads values from a config file.我想创建一个从配置文件中读取值的类。 I'd prefer to use a php array as a config file rather than a .ini one.我更喜欢使用 php 数组作为配置文件而不是 .ini 文件。
What's the best approach for that?最好的方法是什么? using require_once inside a method looks to me a bit odd.在方法中使用 require_once 在我看来有点奇怪。
what I would like to do is a class that reads a config file and exposes this values as properties...我想做的是一个读取配置文件并将这些值公开为属性的类......
thanks for your suggestion谢谢你的建议
To read any ini file in to array:要将任何 ini 文件读入数组:
http://php.net/manual/en/function.parse-ini-file.php http://php.net/manual/en/function.parse-ini-file.php
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);
To use an array through require(require_once):通过 require(require_once) 使用数组:
<?php
// config.php
return ["db" =>"mysql", "folder" => "cache"];
// index.php
$config = require_once("config.php");
In OOP it might look something like that.在 OOP 中,它可能看起来像那样。 Do not have any validations!没有任何验证!
<?php
// path/to/config/file.php
return ['db' => 'mysql'];
// Config.php
class Config
{
public static function getInstance($configFile) {
if (self::$instance == null) {
// check that file exists.
$ext = strtolower(substr($configFile, -3));
if ($ext === "php") {
$data = require($configFile);
} elseif ($ext) === "ini") {
$data = parse_ini_file("sample.ini");
} else {
throw new \Exception('Can nod read config file');
}
self::$instance = new \ArrayObject($data, \ArrayObject::ARRAY_AS_PROPS);
//or
//self::$instance = (object) $data;
}
return self::$instance;
}
private static $instance;
}
// Usage
$config = Config::getInstance('path/to/config/file.php');
echo $config->db;
Most php config files use constants;大多数 php 配置文件使用常量;
define("SITE_NAME", "My Test Site");
to read value;读取值; SITE_NAME SITE_NAME
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.