database.php,getdata.php,Getconf.php 在同级目录
数据库配置文件database.php返回一个数组配置数组
Getconf.php 中Getconf类实现了ArrayAccess接口,构造函数可以获取一个参数$path
getdata.php中$data = new Getconf(),则下一行代码中$data['database']自动触发了类Getconf的实例$data的offsetGet方法并将database作为实参传递给该方法,$data['database']的值为offsetGet方法的返回值$conf[$key]。(可查阅ArrayAccess接口了解)
则offsetGet方法中$conf[$key] = require $this->path.$key.".php"; 引入了同级目录下database.php($this->path为Getconf类构造函数接受的参数,此示例中为空)并赋值给$conf['database'],因配置文件database.php直接返回了一个数组,则
$conf['database']=array(
'host' => 'localhost',
'user' => 'root',
'password' => 'root'
);
则
$data['database']=$conf['database']=array(
'host' => 'localhost',
'user' => 'root',
'password' => 'root'
);
则getdata.php中$data['database']['host']='localhost'
运行getdata.php输出localhost
Getconf.php
<?php
/**
* 通过实现ArrayAccess 达到自定义数组访问方式的效果
*/
class Getconf implements ArrayAccess
{
protected $path;
protected $conf;
function __construct($path='')
{
$this->path = $path;
}
function offsetGet($key)
{
if(empty($conf[$key]))
{
$conf[$key] = require $this->path.$key.".php";
return $conf[$key];
}
}
function offsetExists($key)
{
var_dump($key);
}
function offsetSet($key,$value)
{
var_dump($key);
}
function offsetUnset($key)
{
var_dump($key);
}
}
getdata.php 通过Getconf类以数组方式获取配置文件内指定配置
<?php
require 'Getconf.php';
$data = new Getconf();
echo $data['database']['host'];
database.php 示例数据库配置文件
<?php
return array(
'host' => 'localhost',
'user' => 'root',
'password' => 'root'
);