TP5源码分析前置知识-ArrayAccess接口

1、废话稍作唠叨

对象可以像数组一样使用下标操作

2、ArrayAcess接口需要实现的方法

ArrayAccess {
/* Methods */
#检查偏移位置是否存在
abstract public offsetExists ( mixed $offset ) : bool
#获取一个偏移位置的值
abstract public offsetGet ( mixed $offset ) : mixed
#设置一个偏移位置的值
abstract public offsetSet ( mixed $offset , mixed $value ) : void
#删除一个偏移位置的值
abstract public offsetUnset ( mixed $offset ) : void
}

3、小作demo

class Obj implements ArrayAccess {
    private $container = array();
    public function __construct($arr) {
        $this->container = $arr;
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}
$arr = array(
    "one"   => 1,
    "two"   => 2,
    "three" => 3,
);

$config = new Obj($arr);


var_dump(isset($config["two"]));
var_dump($config["two"]);
unset($config["two"]);
var_dump(isset($config["two"]));
$config["two"] = "A value";
var_dump($config["two"]);
$config[] = 'Append 1';
$config[] = 'Append 2';
$config[] = 'Append 3';
print_r($config);

打印结果:
bool(true)
int(2)
bool(false)
string(7) "A value"
Obj Object
(
    [container:Obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

4、场景使用

例如很多框架里的配置文件

config/database.php

return [
    // 数据库类型
    'type'            => $db_type,
    // 服务器地址
    'hostname'        => $db_host,
    // 数据库名
    'database'        => $db_name,
    // 用户名
    'username'        => $db_user,
    // 密码
    'password'        => $db_pwd,
    // 端口
    'hostport'        => $db_port,
    // 连接dsn
    'dsn'             => '',
    // 数据库连接参数
    'params'          => [],
    // 数据库编码默认采用utf8
    'charset'         => $config['db_charset'],
    // 数据库表前缀
    'prefix'          => $config['db_prefix'],
    // 数据库调试模式
    'debug'           => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    'deploy'          => 0,
    // 数据库读写是否分离 主从式有效
    'rw_separate'     => false,
    // 读写分离后 主服务器数量
    'master_num'      => 1,
    // 指定从服务器序号
    'slave_no'        => '',
    // 自动读取主库数据
    'read_master'     => false,
    // 是否严格检查字段是否存在
    'fields_strict'   => true,
    // 数据集返回类型
    'resultset_type'  => 'array',
    // 自动写入时间戳字段
    'auto_timestamp'  => false,
    // 时间字段取出后的默认时间格式
    'datetime_format' => false,//'Y-m-d H:i:s',
    // 是否需要进行SQL性能分析
    'sql_explain'     => false,
];

Config是一个类,就可以这样使用 Config['sql_explain']

猜你喜欢

转载自blog.csdn.net/weixin_38048544/article/details/106638703