最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

ArrayAccess接口介绍

时间:2014-06-09 16:40来源: 作者: 点击:
在 PHP5 中多了一系列新接口,在 HaoHappy 翻译的系列文章中,你可以了解到他们的应用,同时这些接口和一些实现的 Class 被归为 Standard PHP Library(SPL),在 PHP5 中加入了很多特性,使类的重载 (Overloading

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

下面是 ArrayAccess 的定义:

  1. interface ArrayAccess 
  2. boolean offsetExists($index) 
  3. mixed offsetGet($index) 
  4. void offsetSet($index, $newvalue) 
  5. void offsetUnset($index) 

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

如以下代码:

  1. //Configuration Class 
  2. class Configuration implements ArrayAccess 
  3.  
  4. static private $config
  5.  
  6. private $configarray
  7.  
  8. private function __construct() 
  9. // init 
  10. $this->configarray = array("Binzy"=>"Male""Jasmin"=>"Female"); 
  11.  
  12. public static function instance() 
  13. // 
  14. if (self::$config == null) 
  15. self::$config = new Configuration(); 
  16.  
  17. return self::$config
  18.  
  19. function offsetExists($index
  20. return isset($this->configarray[$index]); 
  21.  
  22. function offsetGet($index) { 
  23. return $this->configarray[$index]; 
  24.  
  25. function offsetSet($index$newvalue) { 
  26. $this->configarray[$index] = $newvalue
  27.  
  28. function offsetUnset($index) { 
  29. unset($this->configarray[$index]); 
  30.  
  31. $config = Configuration::instance(); 
  32. print $config["Binzy"]; 

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

  1. $config = Configuration::instance(); 
  2. print $config["Binzy"]; 
  3. $config['Jasmin'] = "Binzy's Lover"
  4. // config 2 
  5. $config2 = Configuration::instance(); 
  6. print $config2['Jasmin']; 

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

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

(责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容