提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:在看一个开源项目小项目时,发现作者将配置文件 引用了 ArrayAccess 接口,便查询了一番,希望对大家有帮助。
一、ArrayAccess是什么?
能提供给对象像访问数组的能力的接口,在官方文档中的说明已经非常清楚了。建议大家先去官方文档看一下。
官方详情解释可点击:PHP.net
二、使用 ArrayAccess 做一个简单的配置类
这里我做了一个 config 应用类
1.引入类并且实现四个抽象方法
代码如下(示例):
namespace extend;
class Config implements \ArrayAccess
{
private $config = [];
private static $instance;
private $path;
private function __construct()
{
$this->path = __DIR__ . '/../config/';
}
/**
* @return Config array
*/
public static function instance()
{
if (!self::$instance instanceof Config) {
self::$instance = new Config();
}
return self::$instance;
}
/**
* 获取配置信息
* @param string $key
* @param string $field
* @param mixed $default
* @param bool $throw
* @return mixed
* @throws \Exception
*/
public static function getField($key, $field, $default, $throw = false)
{
$result = isset(self::instance()[$key][$field]) ? self::instance()[$key][$field] : $default;
if ($throw && is_null($result)) {
throw new \Exception("{$key} config empty");
}
return $result;
}
private function __clone()
{
// TODO: Implement __clone() method.
}
//实现 offsetExists 方法
public function offsetExists($offset)
{
return isset($this->config[$offset]);
}
//实现 offsetGet 方法
public function offsetGet($offset)
{
if (empty($this->config[$offset])) {
$this->config[$offset] = require $this->path . $offset . '.php';
}
return $this->config[$offset];
}
//实现 offsetSet 方法
public function offsetSet($offset, $value)
{
throw new \Exception('不提供设置配置');
}
//实现 offsetUnset 方法
public function offsetUnset($offset)
{
throw new \Exception('不提供删除配置');
}
}
2.创建一个 config 目录,并且创建一个 config.php 放在 config目录下
config.php 代码如下(示例):
return [
'driver' => 'mysql',
'host' => '192.168.1.108',
'database' => 'webim',
'username' => 'dev_weike',
'password' => '2021china',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => ''
];
3.使用结果
test.php(示例):
require "./extend/Config.php";
$config = extend\Config::instance();
$config = $config['config'];
var_dump($config);
//输出结果
array(8) {
["driver"]=>
string(5) "mysql"
["host"]=>
string(13) "192.168.1.108"
["database"]=>
string(5) "webim"
["username"]=>
string(9) "dev_weike"
["password"]=>
string(9) "2021china"
["charset"]=>
string(4) "utf8"
["collation"]=>
string(15) "utf8_general_ci"
["prefix"]=>
string(0) ""
}
总结
提示:这里对文章进行总结:
如果你的类实现了ArrayAccess接口,那么这个类的对象就可以使用$obj[‘xxx’]这种结构了。
$obj[‘xxx’] 对应调用offsetGet方法。
$obj[‘xxx’] = ‘yyy’ 对应调用offsetSet方法。
isset($obj[‘xxx’]) 对应调用offsetExists方法。
unset($obj[‘xxx’]) 对应调用offsetUnset方法。
再次强调,方法的实现代码,你想怎么写就怎么写。(上面的代码仅供参考)
参考文章:
爱你们的小森–https://www.cnblogs.com/foreverno9/p/8640232.html
PHP.net–https://www.php.net/manual/zh/class.arrayaccess.php