数组式访问-ArrayAccess

  以前对ArrayAccess不是很熟悉,现在整理下下有关ArrayAccess相关的知识,ArrayAccess接口就是提供像访问数组一样访问对象的能力的接口。

接口内容如下:

ArrayAccess {

    //检查一个偏移位置是否存在

    abstract public boolean offsetExists ( mixed $offset );

    //获取一个偏移位置的值

    abstract public mixed offsetGet ( mixed $offset );

    //设置一个偏移位置的值

    abstract public void offsetSet ( mixed $offset , mixed $value );

    //复位一个偏移位置的值

    abstract public void offsetUnset ( mixed $offset );

}

项目中使用,获取网站配置:

<?php
namespace lib;
use mpf\core\Di;
class config implements \ArrayAccess{

//定义存储数据的数组
protected $configs;
public function __construct($configs){
  $this->configs = $configs;
  $configs = \lib\model\Home::getWebConfig();
  foreach( $configs as $config ){
    if( !isset($this->configs[$config[‘sc_key‘]]) ){
    $this->configs[$config[‘sc_key‘]] = $config[‘sc_content‘];
    }
  }
}
public function get($key){
  if( isset($this->configs[$key]) ){
    return $this->configs[$key];
  }elseif( $key == ‘caipiao‘){
    $this->configs[‘caipiao‘] = \lib\model\Home::getLcs();
    return $this->configs[$key];
  }elseif( $key == ‘user_money‘ ){
    if( isset($_SESSION[‘uid‘]) ){
  if( $_SESSION[‘utype‘] == 5 ){
    $sql = ‘select money from inner_user where uid=?‘;
  }else{
    $sql = ‘select money from user where uid=?‘;
  }
    $this->configs[‘user_money‘] = \mpf\core\Di::$Di->db->prepare_query($sql,[getUid()])->fetch(\PDO::FETCH_COLUMN);
    return $this->configs[‘user_money‘];
  }
}
}
public function offsetExists($index){
  return isset($this->configs[$index]);
}
public function offsetGet($index){
  return $this->configs[$index];
}
public function offsetSet($index,$val){
  $this->configs[$index] = $val;
}
public function offsetUnset($index){
  unset($this->configs[$index]);
}
}

这样可以使用config对象来直接访问配置信息内容。

---------------------------------

配置程序:

我们可以通过ArrayAccess利用配置文件来控制程序。

1. 在项目更目录下创建一个config目录 
2. 在config目录下创建相应的配置文件,比如app.php 和 database.php。文件程序如下

app.php

<?php

return [
    ‘name‘ => ‘app name‘,
    ‘version‘ => ‘v1.0.0‘
];

database.php

<?php

return [
    ‘mysql‘ => [
        ‘host‘ => ‘localhost‘,
        ‘user‘ => ‘root‘,
        ‘password‘ => ‘12345678‘
    ]
];

3. Config.php实现ArrayAccess

<?php

namespace Config;

class Config implements \ArrayAccess
{
    private $config = [];

    private static $instance;

    private $path;

    private function __construct()
    {
        $this->path = __DIR__."/config/";
    }

    public static function instance()
    {
        if (!(self::$instance instanceof Config)) {
            self::$instance = new Config();
        }
        return self::$instance;
    }

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

    public function offsetGet($offset)
    {
        if (empty($this->config[$offset])) {
            $this->config[$offset] = require $this->path.$offset.".php";
        }
        return $this->config[$offset];
    }

    public function offsetSet($offset, $value)
    {
        throw new \Exception(‘不提供设置配置‘);
    }

    public function offsetUnset($offset)
    {
        throw new \Exception(‘不提供删除配置‘);
    }
}

$config = Config::instance();

//获取app.php 文件的 name
echo $config[‘app‘][‘name‘].PHP_EOL; //app name

//获取database.php文件mysql的user配置
echo $config[‘database‘][‘mysql‘][‘user‘].PHP_EOL; // root

原文地址:https://www.cnblogs.com/jayce-yin/p/9738607.html

时间: 2024-08-01 18:40:18

数组式访问-ArrayAccess的相关文章

PHP预定义接口中 ArrayAccess 数组式访问接口

<?php class obj implements arrayaccess { private $container = array(); public function __construct () { $this -> container = array( "one" => 1 , "two" => 2 , "three" => 3 , ); } public function offsetSet ( $off

ArrayAccess(数组式访问)接口

接口摘要  ArrayAccess { /* 方法 */ abstract public boolean offsetExists ( mixed $offset ) abstract public mixed offsetGet ( mixed $offset ) abstract public void offsetSet ( mixed $offset , mixed $value ) abstract public void offsetUnset ( mixed $offset ) }

数组形式访问对象

<?php//数组形式访问对对象/** * 1.通过继承PHP内置接口ArrayAccess来实现 * 2.必须实现方法:offsetExists,offsetGet,offsetSet,offsetUnset; */class NewObject implements ArrayAccess{    /**     * 检查一个偏移位置是否存在     * @param mixed $offset     * @return bool     */    public function off

ruby中的链式访问和方法嵌套

先看一道题,这道题是codewars上的一道题,我很早就看到了,但是不会写.等到又看到这道题的时候,我刚看完元编程那本书,觉得是可以搞定它的时候了.废话不多说,先看这道题,题目最开始是为JavaScript写的,但是也放在了ruby语言里面,这个没有关系.题目内容是有一个类Calc,通过链式方法调用,可以实现加减乘除.如图给的四个例子.数字只有0-9,运算只有加减乘除,而且每个运算只有一个操作符.(可以先不看下面,自己先想一下怎么写) 首先,每一个例子都是同样的结构---类名和四个方法.拿第一个

C# 类如何声明索引器以提供对类的类似数组的访问的代码

研发期间,将内容过程中比较常用的内容段做个收藏,如下内容内容是关于 C# 类如何声明索引器以提供对类的类似数组的访问.的内容,希望能对各位有用处. using System;using System.IO; public class FileByteArray{ public FileByteArray(string fileName) { stream = new FileStream(fileName, FileMode.Open); } public void Close() { stre

javascript对象属性和数组的访问

javascript对象属性的访问 假如有对象test:var test = {  "a":1,  "b":2};直接访问对象test的属性a的值,有两种方法: 1.test.a; 2.test["a"];   (注意这里要用引号) 但若是用for/in语句访问对象的属性值,则必须用“[]”运算符啦:    for(m in test){        alert(test[m]);        alert(test.m);   //这里会弹出

数组的访问

通过索引访问数组中的元素 1. 取出数组中的元素 2. 修改数组中的元素 3. 往数组中储存元素 格式: 数组名 [ 数组索引 ] 索引:每一个存储到数组的元素,都会自动的拥有一个编号,从0开始,这个自动编号称为数组索引(index) 注意: 1.直接打印数组名,打印的是数组的地址值 2.索引是从0开始,一直到"数组长度-1"   最大的索引是: 数组长度-1 3.动态方式创建数组,数组中的元素有默认值 整数类型的默认值都是 0             浮点型的默认值是 0.0    

数组的访问形式

/********将数组data[N]中所有元素求和****************/ #define N 10 int data[N],sum,*pData; for(pData=&data[0];pData<&data[N];pData++) { sum+=*pData; } //以上for语句等价于 for(int i=0;i<N;i++) { sum+=Data[i]; }  

php 以数组形式访问对象

官方文档上: ArrayAccess { /* Methods */ abstract public boolean offsetExists ( mixed $offset ) abstract public mixed offsetGet ( mixed $offset ) abstract public void offsetSet ( mixed $offset , mixed $value ) abstract public void offsetUnset ( mixed $offs