当前位置:Gxlcms > PHP教程 > PHP读取配置文件类实例

PHP读取配置文件类实例

时间:2021-07-01 10:21:17 帮助过:19人阅读

本篇文章主要介绍PHP读取配置文件类实例,感兴趣的朋友参考下,希望对大家有所帮助。

具体如下:

<?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 false; 
 } 
 // 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 false; 
 } 
 include ('xmllib.php'); 
 $xml = file_get_contents ( $file ); 
 $data = XML_unserialize ( $xml ); 
 $this->_settings = $data ['settings']; 
 } 
} 
?>

配置例子:

/** 
* 针对PHP的配置,如有配置文件 
*config.php 
<?php 
$db = array(); 
// Enter your database name here: 
$db['name'] = 'test'; 
// Enter the hostname of your MySQL server: 
$db['host'] = 'localhost'; 
?> 
//具体调用: 
include ('settings.php'); //原始环境假设每个类为单独的一个类名.php文件 
// Load settings (PHP) 
$settings = new Settings_PHP; 
$settings->load('config.php'); 
echo 'PHP: ' . $settings->get('db.host') . ''; 
* 
*/ 
 读取INI文件,主要用到parser_ini_file函数,该函数返回一个数组,如第二个参数为true时则返回多维数组
/** 
* ini例子:config.ini 
* 
[db] 
name = test 
host = localhost 
//调用例子: 
$settings = new Settings_INI; 
$settings->load('config.ini'); 
echo 'INI: ' . $settings->get('db.host') . ''; 
*/ 
 读取XML文件,需要用到XML_PARSER,xmllib.php
/** 
* XML例子:config.xml 
<?xml version="1.0" encoding="UTF-8"?> 
<settings> 
<db> 
 <name>test</name> 
 <host>localhost</host> 
</db> 
</settings> 
// Load settings (XML) 
$settings = New Settings_XML; 
$settings->load('config.xml'); 
echo 'XML: ' . $settings->get('db.host') . ''; 
* 
*/ 
 读取YAML格式文件,使用YAML必须使用到SPYC这个库
/** 
YAML配置例子:config.yaml 
db: 
 name: test 
 host: localhost 
// Load settings (YAML) 
$settings = New Settings_YAML; 
$settings->load('config.yaml'); 
echo 'YAML: ' . $settings->get('db.host') . ''; 
*/

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP的文件操作及算法

php可逆加密的方法及原理

php针对字符串的遍历与截取操作技巧

以上就是PHP读取配置文件类实例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行