![]() |
|
||
| | 首页 | 下载中心 | 高手学院 | 视频教程 | 书籍教程 | 模板中心 | 空间评测 | 每日代理 | 站长服务 | 高手论坛 | | |||
![]() |
|||
| ArrayAccess接口介绍 作者:佚名 文章来源:不详 点击数: 更新时间:2005-1-30 | ||||||
![]() ![]() |
||||||
下面是 ArrayAccess 的定义:
由于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 与作者联系。 |
| |
| 文章录入:admin 责任编辑:admin 【发表评论】【告诉好友】【打印此文】【关闭窗口】 | |
|
| | 设为首页 | 加入收藏 | 联系我们 | 合作伙伴 | 友情链接 | 广告投放 | 关于我们 | | ||
![]() |
|
|