当前位置: 首页 > 图文教程 > 网络编程 > PHP > ArrayAccess接口介绍

PHP
php 服务器调试 Zend Debugger 的安装教程
从Web查询数据库之PHP与MySQL篇
php 应用程序安全防范技术研究
php 不同编码下的字符串长度区分
php 生成饼图 三维饼图
PHP 字符截取 解决中文的截取问题,不用mb系列
PHP5 操作MySQL数据库基础代码
php面向对象全攻略 (一) 面向对象基础知识
php面向对象全攻略 (二) 实例化对象 使用对象成员
php面向对象全攻略 (三)特殊的引用“$this”的使用
php面向对象全攻略 (四)构造方法与析构方法
php面向对象全攻略 (五) 封装性
php面向对象全攻略 (六)__set() __get() __isset() __unset()的用法
php面向对象全攻略 (七) 继承性
php面向对象全攻略 (八)重载新的方法
php面向对象全攻略 (九)访问类型
php面向对象全攻略 (十) final static const关键字的使用
php面向对象全攻略 (十一)__toString()用法 克隆对象 __call处理调用错误
php面向对象全攻略 (十二) 抽象方法和抽象类
php面向对象全攻略 (十四) php5接口技术

PHP 中的 ArrayAccess接口介绍


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 104 ::
收藏到网摘: n/a

在 PHP5 中多了一系列新接口。在 HaoHappy 翻译的系列文章中 你可以了解到他们的应用。同时这些接口和一些实现的 Class 被归为 Standard PHP Library(SPL)。在 PHP5 中加入了很多特性,使类的重载 (Overloading) 得到进一步的加强。ArrayAccess 的作用是使你的 Class 看起来像一个数组 (PHP的数组)。这点和 C# 的 Index 特性很相似。

下面是 ArrayAccess 的定义:


interface ArrayAccess
boolean offsetExists($index)
mixed offsetGet($index)
void offsetSet($index, $newvalue)
void offsetUnset($index)

由于PHP的数组的强大,很多人在写 PHP 应用的时候经常将配置信息保存在一个数组里。于是可能在代码中到处都是 global。我们换种方式?

如以下代码:

//Configuration Class class Configuration implements ArrayAccess { static private $config; private $configarray; private function __construct() { // init $this->configarray = array("Binzy"=>"Male", "Jasmin"=>"Female"); } public static function instance() { // if (self::$config == null) { self::$config = new Configuration(); } return self::$config; } function offsetExists($index) { return isset($this->configarray[$index]); } function offsetGet($index) { return $this->configarray[$index]; } function offsetSet($index, $newvalue) { $this->configarray[$index] = $newvalue; } function offsetUnset($index) { unset($this->configarray[$index]); } } $config = Configuration::instance(); print $config["Binzy"];


正如你所预料的,程序的输出是"Male"。
如果我们做下面那样的动作:

$config = Configuration::instance(); print $config["Binzy"]; $config['Jasmin'] = "Binzy's Lover"; // config 2 $config2 = Configuration::instance(); print $config2['Jasmin'];


是的,也正如预料的,输出的将是Binzy's Lover。
也许你会问,这个和使用数组有什么区别呢?目的是没有区别的,但最大的区别在于封装。OO 的最基本的工作就是封装,而封装能有效将变化置于内部。也就是说,当配置信息不再保存在一个 PHP 数组中的时候,是的,应用代码无需任何改变。可能要做的,仅仅是为配置方案添加一个新的策略(Strategy)。:

ArrayAccess 在进一步完善中,因为现在是没有办法 count 的,虽然大多数情况并不影响我们的使用。