This example describes the PHP read configuration file class instance. Share to everyone for your reference. as follows:
<?php class Settings {var $_settings = array ();
function Get ($var) {$var = explode ('. ', $var);
$result = $this->_settings;
foreach ($var as $key) {if (! isset ($result [$key])) {return false;
} $result = $result [$key];
return $result;
function load () {Trigger_error (' not yet implemented ', e_user_error); } class Settings_php extends Settings {function load ($file) {if file_exists ($file) = = False) {return FAL
Se
}//Include file include ($file);
Unset ($file);
Get declared variables $vars = Get_defined_vars ();
Add to Settings array foreach ($vars as $key => $val) {if ($key = = ' this ') continue;
$this->_settings [$key] = $val; }} class Settings_ini extends Settings {function load ($file) {if file_exists ($file) = = False) {return
False
$this->_settings = Parse_ini_file ($file, true); } class Settings_yaml extends Settings {fuNction Load ($file) {if (file_exists ($file) = = False) {return false;
Include (' spyc.php ');
$this->_settings = Spyc::yamlload ($file); } class Settings_xml extends Settings {function load ($file) {if file_exists ($file) = = False) {return FAL
Se
Include (' xmllib.php ');
$xml = file_get_contents ($file);
$data = Xml_unserialize ($xml);
$this->_settings = $data [' Settings '];
}}?>
/** * For PHP configuration, such as the configuration file *config.php <?php $db = Array ();
Enter your database name here: $db [' name '] = ' test ';
Enter the hostname of your MySQL server: $db [' host '] = ' localhost '; ?>//Specific call: include (' settings.php ');
The original environment assumes that each class is a separate class name. php file//Load settings (PHP) $settings = new settings_php;
$settings->load (' config.php '); Echo ' PHP: '. $settings->get (' Db.host ').
''; * */Read the INI file, mainly used to the Parser_ini_file function, the function returns an array, such as the second argument is true to return the multidimensional array/** * INI Example: config.ini * [db] name = Test host =
localhost//Call example: $settings = new Settings_ini;
$settings->load (' Config.ini '); Echo ' INI: '. $settings->get (' Db.host ').
''; * * Read XML file, need to use xml_parser,xmllib.php/** * XML Example: Config.xml <?xml version= "1.0" encoding= "UTF-8"?> <settings > <db> <name>test</name>
1. INI is a bit outdated??
2. XML is better,
3. Yaml is good, but it is not standardized after all.
4. txt to organize their own format, the open is not good.
5. Class serialization. Relatively good, but unfamiliar people use more trouble!
6. PHP Definition Constants (do you not need to modify the data?) )
So: XML is the best.
I hope this article will help you with your PHP program design.