在 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,也許你會問,這個和使用數組有什么區別呢?目的是沒有區別的,但最大的區別在于封裝,最基本的工作就是封裝,而封裝能有效將變化置于內部,也就是說,當配置信息不再保存在一個 PHP 數組中的時候,是的,應用代碼無需任何改變,可能要做的,僅僅是為配置方案添加一個新的策略(Strategy)。
ArrayAccess 在進一步完善中,因為現在是沒有辦法 count 的,雖然大多數情況并不影響我們的使用.
新聞熱點
疑難解答