网站首页 工具软件 操作系统 办公软件 网页制作 PHP教程 script脚本专栏 photoshop教程 其他精品教程
我发布的文章 - 教程搜索 - 交流论坛 - 帮助中心 - 网站首页 网络工具 - 常用工具 - 媒体工具 - 系统工具 - 实用工具 NT/2003 - Win Xp - Win2000 - DOS/Win9x - IE/注册表 - Linux - 苹 果 Office - Word - Excel - PowerPoint - 输入法 - 邮件处理 Flash - Dreamweaver - Fireworks - FrontPage - HTMLCSS 基础文章 - PHP函数 - PHP技巧 - 数据库相关 - 高级应用 - PHP安装 - 转载精华 - 常见问题 综 合 类 - 状 态 栏 - 游 戏 类 - 页面背景 - 页面特效 - 页面导航 - 文本操作 - 文本特效 - 图形特效 - 鼠标特效 - 时间日期 - 密 码 类 文字特效 - 按钮与图标 - 色彩运用 - 滤镜魔法 - 综合实例 XML教程 - DELPHI基础教程 - VB教程
首页 -> PHP教程 -> 高级应用

TOP

ArrayAccess接口介绍
文章内容
相关信息
用户评论
文章内容
在 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 的,虽然大多数情况并不影响我们的使用。

参考:
1. 《PHP5 Power Programming》
2. 《设计模式》
3. 《面向对象分析与设计》


您可以通过 binzywu at gmail dot com 与作者联系。

相关信息
ArrayAccess接口介绍
发布者:mmcbbs
浏览量:252
发布日期:2005-04-10 01:24:09
所属专题:
用户评论
称  呼:
内  容:

广告位

广告招租,欢迎抢订

热门信息

·PHP的十个高级技巧(上)
·php生成WAP页面
·php编写大型网站问题 (转)
·修改Zend引擎实现PHP源码加..
·PHP的十个高级技巧(下)
·PHP的十个高级技巧(中)
·PHP的XML分析函数
·PHP4(windows版本)中的COM函数

推荐信息

·php编写大型网站问题 (转)