代碼詳解php中的ArrayAccess介面

來源:互聯網
上載者:User
slim中的依賴注入基於pimple,於是又去學習了一下pimple。 對比之前自己寫的依賴注入類,pimple有一個很新鮮的用法,不是採用

$container->session_storage = function ($c) {    return new $c['session_storage_class']($c['cookie_name']);};

而是以數組方式進行注入:

$container['session_storage'] = function ($c) {    return new $c['session_storage_class']($c['cookie_name']);};

看源碼時才發現原來訣竅就在php5提供的ArrayAccess介面上。
官方定義:提供像訪問數組一樣訪問對象的能力的介面。
該介面主要定義了四個抽象方法:

abstract public boolean offsetExists ( mixed $offset ) #檢查資料是否存在abstract public mixed offsetGet ( mixed $offset )      #擷取資料abstract public void offsetSet ( mixed $offset , mixed $value )     #設定資料   abstract public void offsetUnset ( mixed $offset ) #刪除資料

如果想讓對象使用起來像一個 PHP 數組,那麼我們需要實現 ArrayAccess 介面

代碼如下:

interface ArrayAccess boolean offsetExists($index) mixed offsetGet($index) void offsetSet($index, $newvalue) void offsetUnset($index)


下面的例子展示了如何使用這個介面,例子並不是完整的,但是足夠看懂,:->

代碼如下:

<?php class UserToSocialSecurity implements ArrayAccess { private $db;//一個包含著資料庫存取方法的對象 function offsetExists($name) { return $this->db->userExists($name); } function offsetGet($name) { return $this->db->getUserId($name); } function offsetSet($name, $id) { $this->db->setUserId($name, $id); } function offsetUnset($name) { $this->db->removeUser($name); } } $userMap = new UserToSocialSecurity(); print "John's ID number is " . $userMap['John']; ?>


實際上,當 $userMap['John'] 尋找被執行時,PHP 調用了 offsetGet() 方法,由這個方法再來調用資料庫相關的 getUserId() 方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.