ArrayAccess介面介紹_PHP教程

來源:互聯網
上載者:User
在 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。
也許你會問,這個和使用數組有什麼區別呢?目的是沒有區別的,但最大的區別在於封裝。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...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.