以前對ArrayAccess不是很熟悉,現在整理下下有關ArrayAccess相關的知識,ArrayAccess接口就是提供像訪問數組一樣訪問對象的能力的接口。
接口內容如下:
ArrayAccess { //檢查一個偏移位置是否存在 abstract html' target='_blank'>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 ); }
項目中使用,獲取網站配置:
?phpnamespace 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
?phpreturn [ name = app name , version = v1.0.0 ];
database.php
?phpreturn [ mysql = [ host = localhost , user = root , password = 12345678 ];
3. Config.php實現ArrayAccess
?phpnamespace 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 文件的 nameecho $config[ app ][ name ].PHP_EOL; //app name//獲取database.php文件mysql的user配置echo $config[ database ][ mysql ][ user ].PHP_EOL; // root
相關教程:PHP視頻教程
以上就是PHP數組式訪問-ArrayAccess示例解析的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答