下面是 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. 《面向对象分析与设计》
http://www.bkjia.com/phpjc/631387.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/631387.htmltecharticle在 php5 中多了一系列新接口。在 haohappy 翻译的系列文章中 你可以了解到他们的应用。同时这些接口和一些实现的 class 被归为 standard php l...