1. 程式人生 > >PHP預定義接口:ArrayAccess

PHP預定義接口:ArrayAccess

array $path 目錄 準備工作 print trac ceo fse 配置

簡介
  • 提供像訪問數組一樣訪問對象的能力的接口。

接口摘要
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 )
}

目錄
  • ArrayAccess::offsetExists — 檢查一個偏移位置是否存在
  • ArrayAccess::offsetGet — 獲取一個偏移位置的值
  • ArrayAccess::offsetSet — 設置一個偏移位置的值
  • ArrayAccess::offsetUnset — 復位一個偏移位置的值

代碼演示

class Obj implements ArrayAccess
{
    private $container = [];

    public function offsetExists($offset): bool
    {
        echo ‘調用‘ . __METHOD__ . ‘方法‘ . PHP_EOL;
        echo print_r(func_get_args(), true);

        return isset($this->container[$offset]);
    }

    public function offsetGet($offset)
    {
        echo ‘調用‘ . __METHOD__ . ‘方法‘ . PHP_EOL;
        echo print_r(func_get_args(), true);

        return $this->container[$offset] ?? null;
    }

    public function offsetSet($offset, $value)
    {
        echo ‘調用‘ . __METHOD__ . ‘方法‘ . PHP_EOL;
        echo print_r(func_get_args(), true);
        $this->container[$offset] = $value;
    }

    public function offsetUnset($offset)
    {
        echo ‘調用‘ . __METHOD__ . ‘方法‘ . PHP_EOL;
        echo print_r(func_get_args(), true);

        unset($this->container[$offset]);
    }
}

//實例化對象
$zhangsan = new Obj();

//賦值
$zhangsan[‘name‘] = ‘張三‘;//調用Obj::offsetSet方法

//輸出
echo $zhangsan[‘name‘] . PHP_EOL;//調用Obj::offsetGet方法

//校驗是否存在
isset($zhangsan[‘name‘]) . PHP_EOL;//調用Obj::offsetExists方法

//刪除數組單元
unset($zhangsan[‘name‘]);//調用Obj::offsetUnset方法

應用案例演示

實現配置文件信息讀取

準備工作:

按照一下給出的目錄結構建立文件

./
├── config
│?? ├── app.php
│?? └── database.php
└── config.php
  • ./config/app.php

    <?php
    return [
        ‘name‘ => ‘app name‘,
        ‘version‘ => ‘v1.0.0‘
    ];
  • ./config/database.php

    <?php
    return [
        ‘mysql‘ => [
            ‘host‘ => ‘localhost‘,
            ‘user‘ => ‘root‘,
            ‘password‘ => ‘12345678‘
        ]
    ];
  • ./config.php
<?php

namespace Config;

final Class Config implements \ArrayAccess
{
    private $config = [];
    private static $instance = null;
    private $path = null;

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

    //單例模式獲取實例
    public static function getInstance()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    //防止被克隆
    private function __clone()
    {
    }

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

    public function offsetGet($offset)
    {
        if (!isset($this->config[$offset]) || 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::getInstance();

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

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

PHP預定義接口:ArrayAccess