前言:
ArrayAccess 是PHP标准库(SPL)提供的一个接口,这意味着我们可以直接调用,该接口使得对对象的访问像数组一样。
接口的形式大概类似于如下:
interface ArrayAccess
{
//判断元素是否存在
function offsetExists($offset);
//获取元素
function offsetGet($offset);
//设置元素
function offsetSet($offset, $value);
//销毁某个元素
function offsetUnset($offset);
}
例子一:
class test implements ArrayAccess
{
private $config = array();
public function __construct()
{
//初始配置
$this->config = array(
'name' => 'LSGO实验室',
'address' => '华北电力大学保定二校',
);
}
public function offsetSet($key, $val)
{
$this->config[$key] = $val;
}
public function offsetExists($key)
{
return isset($this->config[$key]);
}
public function offsetUnset($key)
{
unset($this->config[$key]);
}
public function offsetGet($key)
{
return isset($this->config[$key]) ? $this->config[$key] : null;
}
}
$test = new test;
echo $test['name']; //自动调用 offsetGet()
$test['phone'] = 123456; //自动调用 offsetSet()
echo $test['phone'];
if(!isset($test['leader'])){ //自动调用offsetExists()
$test['leader'] = 'MR. LIU';
unset($test['leader']); //自动调用offsetUnset()
}
有同学会问,像上面这种情况,PHP会不会自动的生成一个 test数组来存储这些值,而不是原来的那个 test 对象?
我们可以用 var_dump() 函数来看看它的接口嘛!
var_dump($test);
返回的是:
看到没有,现在 test还是一个对象,而且我们后面设置的 test[‘phone’] 也进入了该对象内。
例子二:
使用过 PHP 框架的同学应该对框架的配置文件印象很深刻吧,那些配置文件就是一个数组,然后实现配置文件的自动加载,接下来我们模仿一下该行为:
我们创建文件 Config.php
class Config implements ArrayAccess
{
protected $path;//配置文件所在目录
protected $configs = array();//保存我们已经加载过的配置
//传入我们的配置文件所在目录
function __construct($path)
{
$this->path = $path;
}
//获取数组的key
function offsetGet($key)
{
//判断配置项是否加载
if(!isset($this->configs[$key])){
$file_path = $this->path.'/'.$key.'.php';
$config = require $file_path;
$this->configs[$key] = $config;
}
return $this->configs[$key];
}
//设置数组的key
function offsetSet($key, $val)
{
//用这种方式只能修改配置文件,可不能在这里直接修改配置项
throw new \Exception("不能修改配置项!");
}
//检测key是否存在
function offsetExists($key)
{
return isset($this->configs[$key]);
}
//删除数组的key
function offsetUnset($key)
{
unset($this->configs[$key]);
}
}
我们在 Config.php 所在目录下 新建目录 configs ,并在configs 目录下新建文件 database.php,代码如下:
<?php
$config = array(
'mysql' => array(
'type' => 'MySQL',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'dbname' => 'test',
),
'sqlite' => array(
//...
),
);
return $config;
?>
使用配置:
$config = new Config(__DIR__.'/configs');
$database_conf = $config['database'];
var_dump($database_conf);
成功获取到配置文件中的内容。
扫描二维码关注公众号,回复:
2010512 查看本文章