您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

ArrayAccess接口介绍

2024/5/14 7:28:21发布47次查看
在 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,我们换种方式?
如以下代码:
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,也许你会问,这个和使用数组有什么区别呢?目的是没有区别的,但最大的区别在于封装,最基本的工作就是封装,而封装能有效将变化置于内部,也就是说,当配置信息不再保存在一个 php 数组中的时候,是的,应用代码无需任何改变,可能要做的,仅仅是为配置方案添加一个新的策略(strategy)。
arrayaccess 在进一步完善中,因为现在是没有办法 count 的,虽然大多数情况并不影响我们的使用.
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product