網站首頁 語言 會計 網際網路計算機 醫學 學歷 職場 文藝體育 範文
當前位置:學識谷 > 計算機 > php語言

PHP的ArrayAccess介面

欄目: php語言 / 釋出於: / 人氣:2.5W

如果想讓物件使用起來像一個 PHP 陣列,那麼我們需要實現 ArrayAccess 介面,就跟隨本站小編一起去了解下吧,想了解更多相關資訊請持續關注我們應屆畢業生考試網!

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() 方法。