首頁  >  文章  >  後端開發  >  程式碼詳解php中的ArrayAccess接口

程式碼詳解php中的ArrayAccess接口

伊谢尔伦
伊谢尔伦原創
2017-06-29 09:47:261507瀏覽

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&#39;s ID number is " . $userMap[&#39;John&#39;]; 
?>


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

以上是程式碼詳解php中的ArrayAccess接口的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn